Connecting VB 2008 Express to MySQL

You need:

I will assume that you have you have installed software needed.

This will be your database schema

schem

Then create a Windows Application Project in Visual Basic 2008 Express Edition and create a Windows Form similar to this..

vb1

Add the necessary Reference for MySQL Connection

vb2

Then choose the MySQL.Data

vb3

After adding reference, you will now be able to use the imports statement for the mysql controls/objects

This is the source code for the Windows Form

Imports MySql.Data.MySqlClient

Public Class Form1
Dim conn As MySqlConnection
Dim reader As MySqlDataReader
Dim command As MySqlCommand
Dim adapter As MySqlDataAdapter
Dim dt As DataTable

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub fetchData()
Try
command = New MySqlCommand
dt = New DataTable
adapter = New MySqlDataAdapter

If (conn.State = ConnectionState.Closed) Then
setConnection()
End If

command.Connection = conn
command.CommandText = “select * from student”

adapter.SelectCommand = command

reader = command.ExecuteReader

dt.Load(reader)

DataGridView1.DataSource = dt

Catch ex As MySqlException
MessageBox.Show(“Error1: ” & ex.Message)
Finally
reader.Close()
conn.Close()
End Try

End Sub

Private Sub setConnection()
Try
conn = New MySqlConnection
conn.ConnectionString = “Data Source=localhost;Database=tesda;User ID=root;Password=admin”
conn.Open()
Catch ex As MySqlException
MessageBox.Show(“Error1: ” & ex.Message)
End Try
End Sub

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Application.Exit()
End Sub

Private Sub btnFetch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFetch.Click
MessageBox.Show(“Connecting to mysql!”)
setConnection()
fetchData()
End Sub
End Class

Here is the output

vb5

* due to the limitation of the display of the code, if you copy and paste this, your program might not work, because VB can read program codes, line by line. If you happen to split a statement to two or more lines, use the “underscore character” _ at the end of the statement.

* What is important here is the process of the connection and retrieval of data and displaying it to datagridview object