我得到这个错误:
已经有一个打开的DataReader与此命令关联,必须首先关闭
这是我的代码:
String sql_get_completed_tasks = "select * from tasks where Ending_date is not null order by Ending_date asc";
SqlCommand command_get_completed_tasks_ = new SqlCommand(sql_get_completed_tasks, cn);
SqlDataReader reader = command_get_completed_tasks_.ExecuteReader();
while (reader.Read())
{
String sql_insert_completed_tasks_toTheNewTable = "insert into history_of_tasks_achievements values ("+
reader[1] +" , N'"+ reader[2]+"' , @image , N'"+ reader[4] +"' , N'"+reader[5]+"' , N'"+ reader[6]+"' , "+
reader[7] +" , N'"+reader[8]+"' , N'"+reader[9] +"' , "+reader[10]+" , @start_date , @end_date , "+reader[13]+
")";
SqlCommand com_insert_completed_tasks_toTheNewTable = new SqlCommand(sql_insert_completed_tasks_toTheNewTable, cn);
com_insert_completed_tasks_toTheNewTable.Parameters.Add(new SqlParameter("@image", reader[3]));
com_insert_completed_tasks_toTheNewTable.Parameters.Add(new SqlParameter("@start_date", reader[11]));
com_insert_completed_tasks_toTheNewTable.Parameters.Add(new SqlParameter("@end_date", reader[12]));
com_insert_completed_tasks_toTheNewTable.ExecuteNonQuery();
} // end of while loop
reader.Close();
MessageBox.Show("Done");
要跳过此错误,我可以为SqlDataReader
创建暂停或关闭,然后从中断值重新打开吗?什么是最好的解决方案?
这实际上应该只是一条语句,不需要迭代来自select
的结果,只需要使用insert
将它们推回到同一个数据库。
const string sqlInsert =
@"INSERT INTO [history_of_tasks_achievements] (col1, col2, col3, ...)
SELECT col1, col2, col3, ... FROM [tasks] WHERE [Ending_date] IS NOT NULL ORDER BY [Ending_date] ASC";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(sqlInsert, con))
{
con.Open();
var inserted = command.ExecuteNonQuery();
}
请确保在SELECT
和INSERT
之间对齐列,使它们匹配。
在这种情况下,您可以使用using语句。
// set up connection, command
using (var reader = command_get_completed_tasks_.ExecuteReader())
{
// do the reader stuff
reader.Close();
}
// Done