我需要在一个函数中运行几个查询,我是否必须为每个函数创建一个新的SqlConnection?或者有一个连接,但不同的SqlCommands也可以工作?
谢谢,
编辑:这会有用吗?
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作为基础:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。