Untuk dapat membuat koneksi antara Visual Basic 2008 dengan database MYSQL pada local server kita, maka kita harus menambahkan konektor SQL. Bagaimana caranya? Ikuti langkah-langkah berikut:

  1. Anda dapat mendownload MYSQL Connector disini.  Setelah berhasil mendownload, install sampai selesai.
  2. Dari Menu Project pilih Add Reference. Kemudian pilih Browse dan cari lokasi file MySql.Data.dll. Biasanya pada directory: C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.13\Assemblies\v4.5.2
  3. Selanjutnya tinggal membuat coding sebagai berikut:

Buat sebuah file class:

Imports MySql.Data.MySqlClient
Public Class connection
    Private strCon As String = "server=localhost;user id=root;database=cipd"
    Private da As New MySqlDataAdapter
    Private cmd As New MySqlCommand
    Private dt As New DataTable
    Private Function myCon() As MySqlConnection
        Return New MySqlConnection(strCon)
    End Function
    Private conn As MySqlConnection = myCon()
    Property con() As MySqlConnection
        Get
            Return conn
        End Get
        Set(ByVal value As MySqlConnection)
            conn = value
        End Set
    End Property
    Public Sub reload(ByVal sql As String, ByVal dtg As Object)
        With cmd
            .Connection = con
            .CommandText = sql
        End With
        da = New MySqlDataAdapter(sql, con)
        da.Fill(dt)
        dtg.DataSource = dt
    End Sub
End Class

Selanjutnya pada form, coding seperti berikut:

Imports MySql.Data.MySqlClient
Public Class Form1
    Dim Mycon As connection = New connection
    Dim stud As student = New student
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Mycon.con.Open()
            If Mycon.con.State = ConnectionState.Open Then
                MsgBox("connected")
                Mycon.reload("SELECT * FROM tani", DataGridView1)
            Else
                MsgBox("not connected")
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Mycon.con.Close()
    End Sub

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

    End Sub

End Class

 

Referensi:

http://www.uwidigital.com/2016/05/cara-menghubungkan-koneksi-vb-net-dengan-mysql-database/

http://ekasolusi.blogspot.com/2015/06/mengkoneksikan-vbnet-2008-dengan.html

File digunakan:

MySql.Data.dll

Download File

Iklan