Im trying to connect MySql from VB.NET in visual basic 2010. I wanted to query the db just to get one return is response to my proID once I click the button. it successfully show connection has been establish but I can't seems to run any sql query on it. what might have been wrong?
This is the error I got from immediate window:
A first chance exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll
Lets assume num is 1001 from the keypress event.
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
ExecuteNonQuery is used for SQL statements that don't return any data (For example, INSERT, UPDATE, DELETE).
What do you want to achieve? If you want to fetch all records from product
table and display it on a datagrid
, then try this:
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
UPDATE 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