SqlDataReader vb.net保持连接打开

bab*_*oon 2 sql vb.net sqlconnection

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

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

这种类型的连接(与不同的sqlq [查询])我在diffenrent函数中使用了很多,每次我关闭连接.我想优化它,以便获取数据所需的时间更少.我怎么做?

Tim*_*ter 5

最好在完成连接后立即处理/关闭连接.实际上,连接池不会关闭底层物理连接,但只有在关闭时才将此连接标记为可重用.因此,如果您不关闭连接,则无法重复使用,因此池需要创建一个非常昂贵的新物理连接.

所以只有一些小的改进:

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

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