VB.net tutorial
Let us begin ...
you will need to install a library called MySQL Connector. Net 5.2.5:
link: MySQL :: Download Connector/Net
First create a new project in the form and place the following controls:
- 1 Textbox (it will be written the query to be executed)
- A Datagridview (here is where the result will be displayed)
- 2 Buttons (1 to execute the query and another to test the connection to MySQL)
First of all, we declare Imports in the library upstairs, just to not have to keep writing "MySQL.Data.MySQLClient" all the time
thus:
Imports MySQL.Data.MySqlClient
This should be placed immediately before "Public Class Form1" should be the first thing written in your code window.
Well, now we declare a variable with the connection string, who does not know or remember the default connection to MySQL, here goes:
Code:
"Database=database name;Data Source=host;User Id=mpgh;Password=mpgh"
Declaring the variable, we have:
Code:
Dim connstr As String = "Database=database name;Data Source=host;User Id=mpgh;Password=mpgh"
This should be a global variable, declare it outside any function. I suggest that the states immediately below the "Public Class Form1".
As the connection is the same for both functions, we declare another global variable to it
Code:
Dim connection As New MySqlConnection(connStr)
Okay, now let's create a test function connection (actually a routine, not a function), call the TestConnection ()
Code:
Sub TestConnection()
Try
connection.Open()
connection.Close()
MsgBox("Running connection")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The above code is very simple, no? He tries to open and close the connection, if everything goes well, a message that appears all is well, otherwise it is a message containing the error.
Now in the button's onclick event to test connection type "TestConnection ()" and ready
In the OnClick event of the button to execute the query, type:
Code:
Private Sub btn_execute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_execute.Click
Dim query As String = txt_query.text
Dim da As New MySqlDataAdapter(query, connection)
Dim ds As New DataSet
If da.Fill(ds) Then
DataGridView1.DataSource = ds.Tables(0)
End If
connection.Close()
End Sub
This code is also quite simple, it takes the query you wrote in "txt_query" and runs, then he fills the dataset called "ds" with the result and displays the result in "DataGridView1" and closes the connection
Ready! Our example program is finished.
Here's a sample query:
Code:
SELECT * FROM your_table
REMEMBERING: This tutorial is for VB.NET 