코드가 실행시 행동 방법에 대한 몇 가지 세부 사항 :
루프 외부에서 만든 것
SqlCommand
도 사용되지 얻을 않겠다고 값이 덮어지고 유지하는 방법과 유사
// This line declares a variable named Values and sets its value to
// a new array of strings. However, this new array is never used
// because the loop overwrites Values with a new array before doing
// anything else with it.
string[] Values = new string[3];
foreach (string line1 in lines)
{
Values = line1.Split(';');
// At this point in the code, whatever was previously stored in Values has been
// tossed on the garbage heap, and Values now contains a brand new array containing
// the results of splitting line1 on semicolons.
// That means that it is no longer safe to assume how many elements the Values array has.
// For example, if line1 is blank (which often happens at the end of a text file), then
// Values will be an empty array, and trying to get anything out of it will throw an
// exception
string query = "INSERT INTO demooo VALUES ('" + Values[0] + "','" + Values[1] + "','" + Values[2] + "')";
cmd = new SqlCommand(query,con);
cmd.ExecuteNonQuery();
}
. 이 두 선언을 모두 루프 안에 넣는 것이 안전합니다. 다음 코드는이를 수행하고 사용 가능한 값의 수를 줄에서 검색했는지 확인하기 위해 몇 가지 오류 검사를 추가합니다. 길지 않은 행은 건너 뜁니다. 괜찮 으면, 좀 더 복잡한 오류 처리 코드를 만들어야 할 수도 있습니다.
foreach(string line in lines)
{
string[] values = line.split[';'];
if(values.Length >= 3)
{
string query = "INSERT INTO demooo VALUES ('" + Values[0] + "','" + Values[1] + "','" + Values[2] + "')";
using (SqlCommand command = new SqlCommand(query, con))
{
cmd.ExecuteNonQuery();
}
}
}
위의 코드는 웹 응용 프로그램과 같이 사용하는 경우 해커에게 취약 할 수 있습니다. 이처럼 보였다 파일을 처리 한 경우 서버로 전송받을 수있는 어떤 명령에 대한 생각 :
1;2;3
4;5;6
7;8;9') DROP TABLE demooo SELECT DATALENGTH('1
더 안전한 옵션은 이러한 종류의 공격에 대해 보호하는 데 도움이됩니다 매개 변수화 된 쿼리를 사용하는 것입니다. 이들은 인수와 명령을 분리하여 SQL 코드와 같은 인수 값을 전달하지 못하게합니다. 이렇게 설정하는 방법의 예는 다음과 같습니다.
string query = "INSERT INTO demooo VALUES (@val1, @val2, @val3);
using (var command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("@val1", Values[0]);
command.Parameters.AddWithValue("@val2", Values[1]);
command.Parameters.AddWithValue("@val3", Values[2]);
command.ExecuteNonQuery();
}
+1은 SQL 주입을 언급합니다. 그러나 OP의 질문에있는 텍스트는 공백으로 구분되어 있으므로 (예 : 줄 바꿈이 아닌 경우)이 유형의 공격이 훨씬 어려워집니다. –
사실 나는 OP가 배치 삽입을 대신하는 것이 더 좋을 것이라고 생각합니다. 그래도 +1은 아주 자세하게 대답합니다. – Crono