如何使用单个MySQL连接执行多个SQL查询?

时间:2016-08-24 07:33:55

标签: mysql vb.net

Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form4
    Dim MysqlConn As MySqlConnection
    Dim COMMAND As MySqlCommand
    Dim Command1 As MySqlCommand
    Dim reader As MySqlDataReader
    Private Sub Form4_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        MysqlConn = New MySqlConnection
        MysqlConn.ConnectionString = "server=localhost;userid=root;password=asdf1j2k;database=abeetha"
        Try
            MysqlConn.Open()
            Dim sql As String
            Dim sql1 As String
            sql = "SELECT SurName FROM a"
            sql1 = "select UserName from a"
            COMMAND = New MySqlCommand(sql, MysqlConn)
            Command1 = New MySqlCommand(sql, MysqlConn)
            reader = COMMAND.ExecuteReader()
            reader = Command1.ExecuteReader()
            If (reader.Read()) Then
                For i As Integer = 0 To DataGridView1.Rows().Count - 1
                    DataGridView1.Rows(i).Cells(0).Value = reader.GetString("SurName")
                    DataGridView1.Rows(i).Cells(1).Value = reader.GetString("UserName")
                Next
            End If
            MysqlConn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try
    End Sub
End Class

2 个答案:

答案 0 :(得分:0)

在这种情况下,最简单的解决方案是使用单个SQL查询:

sql = "SELECT SurName,UserName FROM a"

然后您只需要一个MySqlCommand

COMMAND = New MySqlCommand(sql, MysqlConn)
reader = COMMAND.ExecuteReader()

如果要分别执行两个不同的SQL查询,还应创建单独的MySqlDataReader

Dim reader1 As MySqlDataReader

然后:

COMMAND = New MySqlCommand(sql, MysqlConn)
'Note that you used the sql variable instead of sql1
Command1 = New MySqlCommand(sql1, MysqlConn)
reader = COMMAND.ExecuteReader()
reader1 = Command1.ExecuteReader()

然后在阅读值时,您应该使用相应的reader

DataGridView1.Rows(i).Cells(0).Value = reader.GetString("SurName")
DataGridView1.Rows(i).Cells(1).Value = reader1.GetString("UserName")

一般编码说明:请使用一致且易于理解的命名,因为使用sqlsql1根本不清楚,也很容易造成错误(例如您使用sql代替sql)犯了错误。使用大写变量名称(例如COMMAND)也不常见,并且可能造成混淆。例如,请参阅Visual Basic Naming Conventions

答案 1 :(得分:0)

  

如果你执行多个查询;最后你可以使用例如

        sql = "SELECT SurName FROM TABLE1;select NAME from TABLE2"
        MySqlCommand COMMAND = New MySqlCommand(sql, MysqlConn)
        dataReader = command.ExecuteReader();