加入收藏 | 设为首页 | 会员中心 | 我要投稿 衡阳站长网 (https://www.0734zz.cn/)- 数据集成、设备管理、备份、数据加密、智能搜索!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

多个SQL查询asp.net c#

发布时间:2021-04-01 02:11:39 所属栏目:MsSql教程 来源:网络整理
导读:我需要在一个函数中运行几个查询,我是否必须为每个函数创建一个新的SqlConnection?或者有一个连接,但不同的SqlCommands也可以工作? 谢谢, 编辑:这会有用吗? using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (Sql

我需要在一个函数中运行几个查询,我是否必须为每个函数创建一个新的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

(编辑:衡阳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读