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

Aik*_*oto 2 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;
}
Run Code Online (Sandbox Code Playgroud)

Son*_*nül 5

使用using声明与否取决于你的CommandTypeTextStoredProcedure.

SqlDataAdapter.Fill 打开连接本身.

DataAdapter填充DataSet

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

还有DbDataAdapter.Fill(DataTable)

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

由于SqlDataAdapter没有实现IDisposable,您不需要使用using语句.

如果你想深入了解,你可以检查QuietClose方法QuietOpen方法的实现;

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();
     }
}
Run Code Online (Sandbox Code Playgroud)