多个SQL查询asp.net c#

前端之家收集整理的这篇文章主要介绍了多个SQL查询asp.net c#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在一个函数中运行几个查询,我是否必须为每个函数创建一个新的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
原文链接:https://www.f2er.com/mssql/84329.html

猜你在找的MsSQL相关文章