我有一个程序同时为MS SQL数据库运行多个查询以执行各种功能。
我有一个后台工作程序正在解析表的更新,一个后台工作程序用于更新流数据,两个datagridviews绑定到每四秒刷新一次的表适配器。
我开始收到这样的错误:
System.ArgumentException: Column 'clearString' does not belong to table Table.
at System.Data.DataRow.GetDataColumn(String columnName)
at System.Data.DataRow.get_Item(String columnName)
正在抛出错误,因为它试图解析的表实际上是datagridview的表。如何将一个查询的结果发送到完全不同的代码块?有谁之前经历过这个吗?有没有办法防止这种情况发生?
我尝试重建表适配器并使用完全不同的连接字符串来运行查询但我仍然遇到相同的错误。
这是多个后台工作者之间可能发生的交叉线程问题吗?
我的应用程序中的所有查询都调用此sql类:
Public Class sql
Public Sub New()
connectionString = My.Settings("My_DataConnectionString")
connection = New SqlConnection(connectionString)
Try
If Not connection.State = ConnectionState.Open Then
connection.Open()
End If
Catch ex As Exception
End Try
End Sub
End Class
然后我创建一个新的sql对象并像这个例子一样运行readTable子:
Dim query As New SqlCommand
Dim tempTable As New DataTable
Dim conn As New NCISsql
query.Parameters.AddWithValue("@username", username.ToLower)
query.CommandText = "SELECT * FROM tblUsers WHERE username = @username"
tempTable = conn.readTable(query)
If tempTable.Rows.Count > Nothing Then
validation = "User Exists"
End If
最后,我的readTable函数在这里:
Public Function readTable(ByVal query As SqlCommand)
Try
If Not connection.State = ConnectionState.Open Then
connection.Open()
End If
Catch ex As Exception
Dim str As String = ex.ToString
End Try
Dim outputTable As New DataTable
'If the connection state is not busy or broken, do work
If connection.State = ConnectionState.Open And Not (connection.State = ConnectionState.Executing Or connection.State = ConnectionState.Fetching Or connection.State = ConnectionState.Broken) Then
query.Connection = connection
Dim sqlAdapter As New SqlDataAdapter(query)
Dim ds As New DataSet
ds.EnforceConstraints = False
Try
sqlAdapter.Fill(ds)
If ds.Tables.Count > Nothing Then
outputTable.BeginLoadData()
outputTable = ds.Tables(0)
outputTable.EndLoadData()
outputTable.AcceptChanges()
Else
count += 1
'Attempt workaround for lost tables
If count < 5 Then
outputTable = readTable(query)
count = 0
End If
End If
ds.Dispose()
Catch ex As Exception
'if failed, try again anyways because sql is not returning the right data
count += 1
If count < 5 Then
outputTable = readTable(query)
count = 0
End If
'log the error
writeError("Failed SQL query:" & query.CommandText, ex.ToString)
query.Dispose()
sqlAdapter.Dispose()
End Try
Try
sqlAdapter.Dispose()
query.Dispose()
Catch ex As Exception
End Try
Else
writeError("Failed SQL connection state", connection.State.ToString)
End If
Try
'close the connection
connection.Close()
Catch ex As Exception
End Try
Return outputTable
End Function
我可能没有提供足够的信息,因为我不知道你们还需要什么。基本上,我从后台工作者A运行查询A并从后台工作者B运行查询B,表B返回到A,表A有时返回到B.
这种情况每5分钟发生4次,每个过程每隔400毫秒启动4次。
我已经内置了足够的错误处理,以防止崩溃应用程序并继续相当顺利,但最终用户可能会出现奇怪的行为。