关于您的代码在运行时如何表现的一些细节:
// 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();
}
与 Values 不断被覆盖的方式类似,在循环之外创建的 SqlCommand 也永远不会被使用。将这两个声明都放在循环中是安全的。下面的代码做到了这一点,并且还添加了一些错误检查以确保从该行中检索到可用数量的值。它会简单地跳过任何不够长的行 - 如果还不行,那么您可能需要自己创建一些更复杂的错误处理代码。
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();
}
}
}
最后一点,如果您在 Web 应用程序之类的东西中使用上面的代码,它可能容易受到黑客攻击。想想如果您正在处理一个看起来像这样的文件,可能会向服务器发送什么命令:
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();
}