管理SQL Server连接

Nea*_*ale 7 .net c# sql-server connection-pooling sqlconnection

SQL连接的最佳实践是什么?

目前我正在使用以下内容:

using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING))
{
    sqlConn.Open();
    // DB CODE GOES HERE
}
Run Code Online (Sandbox Code Playgroud)

我已经读过这是一种非常有效的SQL连接方式.默认情况下,SQL池是活动的,所以我理解的是,当using代码结束时,SqlConnection对象被关闭并处理,但是与DB的实际连接放在SQL连接池中.我错了吗?

Joe*_*orn 14

这就是大部分.需要考虑的其他一些要点:

  • 你在哪里得到你的连接字符串?您不希望在整个地方进行硬编码,您可能需要保护它.
  • 你经常有其他的对象来创建,以及在你真正使用的连接(SqlCommand,SqlParameter,DataSet,SqlDataAdapter),以及你想尽可能长的时间等待打开连接.完整模式需要考虑到这一点.
  • 您希望确保将数据库访问强制插入到自己的数据层类或程序集中.所以常见的做法是将其表示为私有函数调用:

.

private static string connectionString = "load from encrypted config file";
private SqlConnection getConnection()
{
    return new SqlConnection(connectionString);
}
Run Code Online (Sandbox Code Playgroud)

然后像这样写你的样本:

using (SqlConnection sqlConn = getConnection())
{
    // create command and add parameters

    // open the connection
    sqlConn.Open();

   // run the command
}
Run Code Online (Sandbox Code Playgroud)

该示例只能存在于您的数据访问类中.另一种方法是标记它internal并将数据层分布在整个组件上.最重要的是严格执行数据库代码的清晰分离.

一个真正的实现可能如下所示:

public IEnumerable<IDataRecord> GetSomeData(string filter)
{
    string sql = "SELECT * FROM [SomeTable] WHERE [SomeColumn] LIKE @Filter + '%'";

    using (SqlConnection cn = getConnection())
    using (SqlCommand cmd = new SqlCommand(sql, cn))
    {
        cmd.Parameters.Add("@Filter", SqlDbType.NVarChar, 255).Value = filter;
        cn.Open();

        using (IDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                yield return (IDataRecord)rdr;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我还能够"堆叠" 对象cncmd对象的创建,从而减少嵌套并仅创建一个范围块.

最后,请注意yield return在此特定示例中使用代码.如果您调用该方法并且不立即完成您的DataBinding或其他用途,则可能会长时间保持连接打开状态.一个例子是在LoadASP.NET页面的情况下使用它来设置数据源.由于实际的数据绑定事件直到稍后才会发生,因此您可以将连接打开的时间比需要的时间长得多.