Pau*_*ulG 11 .net c# sqldatareader
如果我想在不同的表上运行多个SELECT查询,我可以为所有这些表使用相同的SqlDataReader和SqlConnection吗?以下是明智的吗?(我输入的速度很快,所以缺少try/catch):
MySqlCommand myCommand = new MySqlCommand("SELECT * FROM table1", myConnection);
myConnection.Open();
SqlDataReader myDataReader = myCommand.ExecuteReader();
while(myReader.Read())
{
//Perform work.
}
myCommand.commandText = "SELECT * FROM table2";
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
//Perform more work
}
myReader.Close();
myConnection.Close();
Run Code Online (Sandbox Code Playgroud)
非常感谢.
Chr*_*lor 23
只要不尝试在不同线程的同一连接上并发执行多个查询,就可以为每个连接使用相同的连接.
对于数据阅读器,您实际上并没有重新使用阅读器,每次调用都会ExecuteReader返回新阅读器的新实例,您重复使用的只是维护对阅读器的引用的变量.这里存在一个问题,你只是明确地关闭了最后一个读者,并且在稍后的某个时间留下了第一个读者.
您也可以重复使用Command,但请记住,如果您提供参数等,则需要清除它们以用于下一个查询,除非它们也适用于下一个查询.
您应该使用try/finally块来确保清理资源,或者这是对代码的快速更改,以便使用using语句来确保资源清理,即使存在阻止其余代码执行的异常也是如此.
using (var myConnection = GetTheConnection())
{
myConnection.Open();
var myCommand = new MySqlCommand("SELECT * FROM table1", myConnection))
using (var myDataReader = myCommand.ExecuteReader())
{
while(myReader.Read())
{
//Perform work.
}
} // Reader will be Disposed/Closed here
myCommand.commandText = "SELECT * FROM table2";
using (var myReader = myCommand.ExecuteReader())
{
while(myReader.Read())
{
//Perform more work
}
} // Reader will be Disposed/Closed here
} // Connection will be Disposed/Closed here
Run Code Online (Sandbox Code Playgroud)
注意:GetTheConnection只是一个占位符函数,用于获取连接实例所使用的机制.