我需要调用一个函数来执行一些查询,同时打开另一个连接并执行事务。
好的,我知道这很奇怪,这里有一些代码:
主要部分:
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
Dim transaction As SqlTransaction
transaction = connection.BeginTransaction("myTransaction")
command.Connection = connection
command.Transaction = transaction
command.CommandText = sSQL
Try
command.ExecuteNonQuery()
Dim functionResult As String = myFunction(param1, param2)
If functionResult <> "" Then
'error! i need to rollback the first query done here!
transaction.Rollback()
else
transaction.Commit()
End If
Catch ex As Exception
transaction.Rollback()
End Try
End If
End Using
myFunction做了很多事情,还有很多查询。每个查询都需要重新打开连接(这次没有事务),但是每次我尝试在我的函数中执行第一个查询时,我都会从数据库中收到超时错误(30 秒后)。
我知道我可以在已打开的连接中并使用已打开的连接“复制粘贴”所有 myFunction 代码来完成这项工作,但我不止一次使用该函数,我不想弄乱我的代码。
我该如何解决这个问题?
编辑以获取更多信息:那是我正在使用的代码的简化版本,但这里是“myFunction”所做的简化版本:
Dim connectionString As String = "my connection string"
Dim queryString As String = "SELECT id FROM foo WHERE param1 = @myValue"
Dim ds As DataSet = New DataSet()
Try
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
command.CommandText = queryString
command.Parameters.Add("@myValue", SqlDbType.Int).Value = 10
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = command
adapter.Fill(ds, "randomName")
If ds.Tables("randomName").Rows.Count < 0 Then
'error!
connection.Close()
Return "error"
End If
End Using
Catch ex As Exception
Return "Database error - " & ex.Message
End Try
代码执行(即使在调试中)在adapter.Fill(ds, "randomName")
命令上冻结 30 秒,之后我得到一个超时错误