2016-08-24 174 views
-1
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 
+0

使您的代碼可讀性和易於理解。並閱讀這[問] – Muj

回答

0

在這種情況下,最簡單的解決方法是使用一個SQL查詢:如果你想要做的兩個不同的

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

sql = "SELECT SurName,UserName FROM a" 

然後,你只需要一個MySqlCommand 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

0

如果您執行多個查詢;在去年ü可以使用例如

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