2012-03-27 89 views
1

我試圖從Visual Basic 2010中的VB.NET連接MySql。我想查詢數據庫只是爲了得到一個返回是我的proID響應,一旦我點擊按鈕。它成功顯示連接已建立,但我似乎無法運行任何SQL查詢。什麼可能是錯的?在vb.net連接到mysql

這是我從即時窗口得到了錯誤:

A first chance exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll 

讓我們假設從按鍵事件num是1001。

Public Class Form1 
    Private connStr As String = "server=localhost;" & _ 
       "user id=root;Password=1234561;" & _ 
       "database = test" 
    Dim num As Integer 


Private Sub TextBox1_keypress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress 
    Dim str As String 
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then 
     str = TextBox1.Text 
     Dim splitVals As String() = str.Split(" ") 
     num = splitVals(1) 
    End If 
End Sub 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim query As String = "SELECT * FROM products" 
    Dim con As New MySqlConnection(connStr) 
    Dim cmd As New MySqlCommand(query) 
    Try 
     con.Open() 
     MessageBox.Show("Database Connected") 
     cmd.ExecuteNonQuery() 
     cmd.Connection.Close() 

     con.Close() 
    Catch ex As Exception 
     Console.WriteLine(ex.Message) 
    End Try 
End Sub 

End Class 

回答

0

的ExecuteNonQuery用於SQL語句不返回任何數據(例如,INSERT,UPDATE,DELETE)。

你想實現什麼?如果你想從product表獲取所有記錄,並在datagrid顯示它,那就試試這個:

Using xConn as New MySqlConnection(connStr) 
    Using xComm as new MySQLCommand() 
     xComm.Connection = xConn 
     xComm.CommandText = "SELECT * FROM products" 
     Using xAdapter as new MySQLDAtaAdapter(xComm) 
      Dim ds as new Dataset 
      xConn.Open() 
      xAdapter.Fill(ds) 
      datagridview1.datasource = ds.tables(0) 
     End Using 
    End Using 
End Using 

更新1

Dim xPrice as Integer = 0 
Using xConn as New MySqlConnection(connStr) 
    Using xComm as new MySQLCommand() 
     xComm.Connection = xConn 
     xComm.CommandText = "SELECT ProductPrice FROM products WHERE proID = @xID" 
      xComm.Parameters.AddWithValue("xID", "Value Here") 
      xConn.Open() 
      xPrice = CInt(xComm.ExecuteScalar()) 
      xConn.Close 
    End Using 
End Using 

Msgbox xPrice 
+0

我只是想從數據庫中獲得1場。 我得到了proID,並且我想取價格。是否有可能只提取1場? – 2012-03-27 08:11:19

+0

當然:)看到我更新的答案。它使用'ExecuteScalar'。 – 2012-03-27 08:48:02

+0

非常感謝!但如果我期待String而不是Int? – 2012-03-27 10:02:57

1

試試這個代碼:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim query As String = "SELECT * FROM products" 
    Dim con As New MySqlConnection(connStr) 
    Dim da as New MySqlDataAdapter() 
    Dim ds as New DataSet 
    Try 
     con.Open() 
     MessageBox.Show("Database Connected") 
     da=New MySqlDataAdapter(query,con) 
     da.fill(ds,"products") 
     DataGridView1.DataSource=ds.Tables("products") 
     con.Close() 
    Catch ex As Exception 
     Console.WriteLine(ex.Message) 
    End Try 
End Sub