我正在执行一个简单的练习,即打开SQL Server数据库连接,从DataReader对象中提取表的第一条记录,然后关闭该对象。但是,我注意到在关闭连接时有大约5秒左右的延迟。但是,延迟仅在命令对象执行指定查询后发生。我曾经在这样的设置中工作,并且不记得关闭连接时有这么长的延迟。
Public Sub TestDb()
Dim cnStrBuilder As New SqlClient.SqlConnectionStringBuilder
Dim cn As New SqlClient.SqlConnection
Dim sqlSelectName As New SqlClient.SqlCommand
Dim drName As SqlClient.SqlDataReader
Dim newName As New SymName
Dim i As Integer
cnStrBuilder.UserID = "sa"
cnStrBuilder.ConnectTimeout = 30
cnStrBuilder.Password = ""
cnStrBuilder.PersistSecurityInfo = True
cnStrBuilder.DataSource = "EMARKET\FL_DB"
cnStrBuilder.InitialCatalog = "EmailMarketing"
sqlSelectName.CommandType = CommandType.Text
sqlSelectName.CommandText = "SELECT * FROM [NAME]"
System.Console.WriteLine(cnStrBuilder.ConnectionString)
cn.ConnectionString = cnStrBuilder.ConnectionString
Try
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
System.Console.WriteLine("Connection success")
sqlSelectName.Connection = cn
System.Console.WriteLine("Execute Reader")
drName = sqlSelectName.ExecuteReader
If drName.HasRows = True Then
System.Console.WriteLine("Read Row")
drName.Read()
For i = 0 To drName.FieldCount - 1
Console.WriteLine(drName.Item(i).ToString)
Next
End If
System.Console.WriteLine("Closing connection")
sqlSelectName.Connection.Close()
Catch ex As Exception
System.Console.WriteLine("Something Happened")
System.Console.WriteLine(ex.Message)
End Try
System.Console.WriteLine("Done.")
End Sub
如果我省略了行
'System.Console.WriteLine("Execute Reader")
'drName = sqlSelectName.ExecuteReader
'
'If drName.HasRows = True Then
' System.Console.WriteLine("Read Row")
' drName.Read()
'
' For i = 0 To drName.FieldCount - 1
' Console.WriteLine(drName.Item(i).ToString)
' Next
'End If
连接几乎立即关闭。是什么赋予了?我已将其缩小到导致连接延迟的.ExecuteReader
行关闭的位置。 导致延迟的原因是什么?如何解决?
答案 0 :(得分:1)
您告诉SQL Server检索整个表。然而,在第一行之后,您停止并关闭连接。和你一样,我希望连接能够立即关闭,但也许服务器正在忙着将表格转移到可以快速返回数据的地方。
如果您只询问服务器一行,连接是否仍然缓慢关闭? F.e。
sqlSelectName.CommandText = "SELECT TOP 1 * FROM [NAME]"
答案 1 :(得分:0)
通常,您应该在使用包含连接对象的语句中包装任何实现IDisposable的对象。我会尝试实现以下来自MSDN的内容:
http://msdn.microsoft.com/en-us/library/y6wy5a0f.aspx#Y400
Public Sub CreateCommand(ByVal queryString As String, _
ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlDataReader = _
command.ExecuteReader(CommandBehavior.CloseConnection)
While reader.Read()
Console.WriteLine("{0}", reader(0))
End While
End Using
End Sub