多个SQL查询asp.net c#
发布时间:2021-04-01 06:01:21  所属栏目:MsSql教程  来源:网络整理 
            导读:我需要在一个函数中运行几个查询,我是否必须为每个函数创建一个新的SqlConnection?或者有一个连接,但不同的SqlCommands也可以工作? 谢谢, 编辑:这会有用吗? using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (
                
                
                
            | 我需要在一个函数中运行几个查询,我是否必须为每个函数创建一个新的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(编辑:南平站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 

