我需要在一个函数中运行几个查询,我是否必须为每个函数创建一个新的sqlConnection?或者有一个连接,但不同的sqlCommands也可以工作?
谢谢,
编辑:这会有用吗?
@H_404_6@using (sqlConnection conn = new sqlConnection(connectionString)) { conn.Open(); using (sqlCommand cmd = new sqlCommand(query1,conn)) { cmd.ExecuteNonQuery(); } using (sqlCommand cmd = new sqlCommand(query2,conn)) { cmd.ExecuteNonQuery(); } using (sqlCommand cmd = new sqlCommand(query3,conn)) { cmd.ExecuteNonQuery(); } }解决方法
使用
MDSN Documentation作为基础:
@H_404_6@using (sqlConnection connection = new sqlConnection(connectionString))
{
connection.Open();
string sql1 = "SELECT ID,FirstName,LastName FROM VP_PERSON";
string sql2 = "SELECT Address,City,State,Code FROM VP_ADDRESS";
using (sqlCommand command = new sqlCommand(sql1,connection))
{
//Command 1
using (sqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
using (sqlCommand command = new sqlCommand(sql2,connection))
{
//Command 1
using (sqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
// If you don't using using on your sqlCommands you need to dispose of them
// by calling command.Dispose(); on the command after you're done.
} // the sqlConnection will be disposed