在vb.net中连接到mysql

时间:2012-03-27 07:34:09

标签: mysql vb.net visual-studio connector-net

我试图在Visual Basic 2010中从VB.NET连接MySql。我想查询数据库只是为了得到一个返回是我的proID响应一旦我点击按钮。它成功显示连接已建立但我似乎无法运行任何SQL查询。什么可能是错的?

这是我从即时窗口得到的错误:

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

让我们假设来自keypress事件的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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