【问题标题】:SqlDataReader vb.net keep connection openSqlDataReader vb.net 保持连接打开
【发布时间】:2012-11-26 19:23:36
【问题描述】:

我正在使用此代码获取数据:

 Dim connetionString As String
    Dim connection As SqlConnection
    Dim sqlq As String

    sqlq = "select top 1 * from table1 where smth"

    Dim ds As New DataSet
    connetionString = "Data Source=db;Initial Catalog=ic;User ID=id;Password=pass"
    connection = New SqlConnection(connetionString)

    Try
        Using connection
            Dim command As SqlCommand = New SqlCommand(sqlq, connection)
            connection.Open()
            Dim reader As SqlDataReader = command.ExecuteReader()
            If reader.HasRows Then
                Do While reader.Read()
                    x = reader.GetString(5)
                Loop
            End If
            reader.Close()
        End Using
    Catch ex As Exception
    End Try

这种类型的连接(使用不同的sqlq [查询])我在不同的函数中使用了很多,每次我关闭连接时。我想对其进行优化,以减少获取数据的时间。我该怎么做?

【问题讨论】:

  • 这是一个非常非常糟糕的主意。 不要保持数据库连接打开的时间超过您绝对需要的时间。最佳做法是:尽可能晚打开,做好你的工作,尽快再次关闭
  • 我正在考虑只要应用程序正在运行就保持连接打开,因为我需要尽快获取数据,这里的时间非常重要。
  • 正如我所说:这是一个非常糟糕的主意 - 不要这样做。说真的。

标签: sql vb.net sqlconnection


【解决方案1】:

最好在完成连接后立即释放/关闭连接。实际上connection-pool 不会关闭底层物理连接,而只会在关闭时将此连接标记为可重用。因此,如果您不关闭连接,它就不能被重用,因此池需要创建一个非常昂贵的新物理连接。

所以只有一些小的改进:

Const sql = "select top 1 * from table1 where smth"
Dim table As New DataTable()

Using con = New SqlConnection("Data Source=db;Init ....")
    Using command = New SqlCommand(sql, con)
        Using da= New SqlDataAdapter(command)
            da.Fill(table)
        End Using
    End Using
End Using

您应该对任何实现IDisposable 的对象使用Using。您不应使用空的 Catch 块。

【讨论】:

    【解决方案2】:

    请改用connection pooling

    默认情况下,只要连接字符串相同,就会从同一个连接池中获取连接。

    连接池会在短时间内保持不需要的连接打开,并在下一次请求时返回该连接,因此您无需考虑打开连接所需的时间。

    保持连接打开的时间超过您需要的时间是个坏主意,因为它会消耗资源,而且通常一些服务器可以接受有限的连接。

    【讨论】:

    • “使用连接池代替” 有点误导,因为默认情况下在 ADO.NET 中启用了连接池。
    • 同意,默认开启,我的意思是不要关闭! :)