这个问题可能由于循环过程中发生了未处理的异常而导致。为了确定是在哪一步出错了,我们可以在循环中加入try-catch语句来捕捉异常并输出错误信息。另外,为了避免在循环过程中出现数据库连接断开的情况,我们可以每次循环前都打开一个新的连接,并在循环结束后关闭连接。下面是一个示例代码:
using System.Data.SqlClient;
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString);
try { connection.Open();
for (int i = 0; i < myRecords.Count; i++)
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
// 根据需要向不同的表添加记录
if (i % 2 == 0)
{
command.CommandText = "INSERT INTO Table1 (Column1, Column2) VALUES (@value1, @value2)";
}
else
{
command.CommandText = "INSERT INTO Table2 (Column1, Column2) VALUES (@value1, @value2)";
}
// 设置参数并执行命令
command.Parameters.AddWithValue("@value1", myRecords[i].Value1);
command.Parameters.AddWithValue("@value2", myRecords[i].Value2);
command.ExecuteNonQuery();
}
} catch (Exception ex) { // 输出错误信息 Console.WriteLine(ex.Message); } finally { // 关闭连接 connection.Close(); }