mysql – SQL Queries and Threading

12/01/2018


I have to execute several SQL queries and I want to use Threads for this, because this queries have to be executed every 1 second to update or get some different values of the database.

When I try to execute my code, I get the following Error:

WindowsApplication1.vshost.exe Error: 0 : There is already an open
DataReader associated with this Connection which must be closed first.

I have read on stackoverflow, that the Connection should ALWAYS be opened as late as possible and be closed as fast as possible.

Is there any solution for this Problem?

Here is my code:

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

قالب وردپرس