C# There is already an open DataReader associated with this Connection which must be closed first
This error occurs when there is an attempt to execute a new query on a database connection before the previous query's DataReader has been closed.
To resolve this error, you can do the following:
-
Make sure to close any open DataReader before executing a new query on the same connection.
-
Use the SqlDataReader.NextResult() method to move to the next result set if you need to execute multiple queries on the same connection.
-
Use the using statement to automatically dispose of the DataReader and close the connection after the query has been executed.
Example:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM Table1", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// do something with the data
}
}
}
// execute another query after closing the previous DataReader
using (SqlCommand command = new SqlCommand("SELECT * FROM Table2", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// do something with the data
}
}
}
}
``
原文地址: https://www.cveoy.top/t/topic/hq1a 著作权归作者所有。请勿转载和采集!