我必须执行几个SQL查询,我想为此使用Threads,因为这个查询必须每1秒执行一次,以更新或获取数据库的某些不同值。
当我尝试执行我的代码时,出现以下错误:
WindowsApplication1.vshost.exe错误:0:已经打开了 与此Connection关联的DataReader必须先关闭。
我已阅读stackoverflow,应尽可能晚地打开Connection 始终,并尽快关闭。
这个问题有解决方法吗?
这是我的代码:
Imports MySql.Data.MySqlClient
Imports System.Threading
Public Class Form1
Private server As String = Nothing
Private pass As String = Nothing
Private user As String = Nothing
Private port As String = Nothing
Private db As String = Nothing
Dim Thread1 As Thread
Dim Thread2 As Thread
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim reader As MySqlDataReader
Public Sub New()
Me.server = "localhost"
Me.user = "root"
Me.pass = ""
Me.port = "3306"
Me.db = "diagnosedb"
cmd.Connection = con
con.ConnectionString = "Server = " & Me.server & ";
Port = " & Me.port & ";
Database = " & Me.db & ";
Uid = " & Me.user & ";
Pwd = " & Me.pass & ";"
Thread1 = New Thread(AddressOf Querie1)
Thread2 = New Thread(AddressOf Querie2)
Thread1.Start()
Thread2.Start()
End Sub
Private Sub Querie1()
cmd.CommandText = "UPDATE teileliste
SET verschleis = 500
WHERE ID = 1;"
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Querie2()
cmd.CommandText = "UPDATE teileliste
SET verschleis = 0
WHERE ID = 20;"
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class
答案 0 :(得分:0)
在this.get('change').download().then(() => {});
和Querie1
方法中创建并关闭新连接。一个连接不能进行多个并发操作。 (即使你可以,你也在关闭两种方法中的连接。一种方法可能会尝试关闭它而另一种方法正在使用它。)
.NET Framework擅长管理连接。当您在代码中打开和关闭它们时,它在幕后实际上保持连接打开一段时间。这称为线程池。当您关闭连接时,它实际上暂时保持打开状态。当您打开新连接时,它实际上可能会给您相同的连接。
大多数时候我们不需要注意这一点。我们所做的就是尽可能地创建一个新的连接,当我们打开并使用它时,然后尽快关闭(处理)它。