调用存储过程时需要Connection.Open()吗?

时间:2014-09-19 07:11:00

标签: c# sql stored-procedures database-connection

Normaly我会使用“Using”或者只使用connection.open()和connection.close()。但是当我调用存储过程时,不需要这样做。怎么会? (是的,下面的codesnippit无需使用或打开即可使用)。

try {
    SqlCommand cmd = new SqlCommand("***", connectionSiteDb);
    DataTable dt = new DataTable();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter("@ProcessSegmentID", ProcessSSegmentID));
    cmd.Parameters.Add(new SqlParameter("@PO_RecipeID", PO_RecipeID));
    cmd.Parameters.Add(new SqlParameter("@ProductSegmentVersion", ProductSegmentVersion));


    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    da.Fill(dt);
    return dt;
}
catch (Exception e) {
     Console.WriteLine(e);
     return null;
}

1 个答案:

答案 0 :(得分:5)

是否使用using statement取决于CommandTypeText还是StoredProcedure

SqlDataAdapter.Fill会自行打开连接。

来自Populating a DataSet from a DataAdapter

  

Fill方法隐式打开DataAdapter的Connection   如果发现连接尚未打开,则使用。如果填写   打开连接,它也将在Fill时关闭连接   完了。这可以在处理单个代码时简化代码   填充或更新等操作。

另外DbDataAdapter.Fill(DataTable)

  

在   与SELECT语句关联的连接对象必须有效,   但不需要打开。如果之前连接已关闭   调用Fill,打开它以检索数据,然后关闭。如果   在调用Fill之前连接已打开,它仍保持打开状态。

由于SqlDataAdapter未实现IDisposable,因此您无需在其中使用using语句。

如果您想深入了解,可以查看QuietClose methodQuietOpen method实施;

static private void QuietClose(IDbConnection connection, ConnectionState originalState)
{
      // close the connection if:
      // * it was closed on first use and adapter has opened it, AND
      // * provider's implementation did not ask to keep this connection open
      if ((null != connection) && (ConnectionState.Closed == originalState)) {
          // we don't have to check the current connection state because
          // it is supposed to be safe to call Close multiple times
          connection.Close();
      }
}

// QuietOpen needs to appear in the try {} finally { QuietClose } block
// otherwise a possibility exists that an exception may be thrown, i.e. ThreadAbortException
// where we would Open the connection and not close it
static private void QuietOpen(IDbConnection connection, out ConnectionState originalState)
{
     originalState = connection.State;
     if (ConnectionState.Closed == originalState) {
         connection.Open();
     }
}