简体   繁体   English

管理SQL Server连接

[英]Managing SQL Server Connections

What is the the best practice for SQL connections? SQL连接的最佳实践是什么?

Currently I am using the following: 目前我正在使用以下内容:

using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING))
{
    sqlConn.Open();
    // DB CODE GOES HERE
}

I have read that this is a very effective way of doing SQL connections. 我已经读过这是一种非常有效的SQL连接方式。 By default the SQL pooling is active, so how I understand it is that when the using code ends the SqlConnection object is closed and disposed but the actual connection to the DB is put in the SQL connection pool. 默认情况下,SQL池是活动的,因此我理解的是,当using代码结束时, SqlConnection对象被关闭并处理,但是与DB的实际连接被放入SQL连接池中。 Am i wrong about this? 我错了吗?

That's most of it. 这就是大部分。 Some additional points to consider: 需要考虑的其他一些要点:

  • Where do you get your connection string? 你在哪里得到你的连接字符串? You don't want that hard-coded all over the place and you may need to secure it. 您不希望在整个地方进行硬编码,您可能需要保护它。
  • You often have other objects to create as well before your really use the connection ( SqlCommand , SqlParameter , DataSet , SqlDataAdapter ), and you want to wait as long as possible to open the connection . 在真正使用连接( SqlCommandSqlParameterDataSetSqlDataAdapter )之前,您通常还要创建其他对象,并且您希望尽可能长时间地等待打开连接 The full pattern needs to account for that. 完整模式需要考虑到这一点。
  • You want to make sure your database access is forced into it's own data layer class or assembly. 您希望确保将数据库访问强制插入到自己的数据层类或程序集中。 So a common thing to do is express this as a private function call: 所以常见的做法是将其表示为私有函数调用:

.

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

And then write your sample like this: 然后像这样写你的样本:

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

    // open the connection
    sqlConn.Open();

   // run the command
}

That sample can only exist in your data access class. 该示例只能存在于您的数据访问类中。 An alternative is to mark it internal and spread the data layer over an entire assembly. 另一种方法是将其标记为internal并将数据层分布在整个程序集上。 The main thing is that a clean separation of your database code is strictly enforced. 最重要的是严格执行数据库代码的清晰分离。

A real implementation might look like this: 一个真正的实现可能如下所示:

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;
            }
        }
    }
}

Notice that I was also able to "stack" the creation of the cn and cmd objects, and thus reduce nesting and only create one scope block. 请注意,我还能够“堆叠” cncmd对象的创建,从而减少嵌套并仅创建一个范围块。

Finally, a word of caution about using the yield return code in this specific sample. 最后,请注意在此特定示例中使用yield return代码。 If you call the method and don't complete your DataBinding or other use right away it could hold the connection open for a long time. 如果您调用该方法并且不立即完成DataBinding或其他用途,则可能会长时间保持连接打开状态。 An example of this is using it to set a data source in the Load event of an ASP.NET page. 一个例子是使用它在ASP.NET页面的Load事件中设置数据源。 Since the actual data binding event won't occur until later you could hold the connection open much longer than needed. 由于实际的数据绑定事件直到稍后才会发生,因此您可以将连接打开的时间比需要的时间长得多。

Microsoft's Patterns and Practices libraries are an excellent approach to handling database connectivity. Microsoft的模式和实践库是处理数据库连接的绝佳方法。 The libraries encapsulate most of the mechanisms involved with opening a connection, which in turn will make your life easier. 这些库封装了打开连接所涉及的大部分机制,这反过来又会让您的生活更轻松。

Your understanding of using is correct, and that method of usage is the recommended way of doing so. 您对使用的理解是正确的,并且建议使用该方法。 You can also call close in your code as well. 您也可以在代码中调用close。

Also : Open late, close early. 另外:开放较晚,提前关闭。

Don't open the connection until there are no more steps left before calling the database. 在调用数据库之前没有剩下的步骤之前,请不要打开连接。 And close the connection as soon as you're done. 完成后立即关闭连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM