Jumat, 12 Agustus 2011

Koneksi VB 6.0 ke MySQL

Sebelum membuat koneksi ke mysql kita bisa membuat form untuk setting server, tujuannya agar tidak mengganti secara manual apabila program di jalankan di komputer lain yang servernya berbeda.

Membuat Form Setting Server
  1. buat form seperti gambar di bawah ini :
  2. Setelah membuat setting server tambahkan References Microsoft ActivX Data Objects 2.0 Library, caranya pilih menu Project + References + pilih Microsoft ActivX Data Objects 2.0 Library dengan mencentangnya + OK.
  3. Berikut adalah contoh kode program untuk menyimpan isi dari varibel-variabel setting server :
    Private Sub cmdKeluar_Click()
    Unload Me
    Me.Hide
    End Sub
    Private Sub cmdSimpan_Click()
    SaveSetting App.EXEName, "x", "server", txtServer.Text
    SaveSetting App.EXEName, "x", "uid", txtUserID.Text
    SaveSetting App.EXEName, "x", "port", txtPort.Text
    SaveSetting App.EXEName, "x", "password", txtPassword.Text
    txtServer.Text = ""
    txtPort.Text = ""
    txtUserID.Text = ""
    txtPassword.Text = ""
    End Sub
    Private Sub Form_Load()
    On Error GoTo errhandler
    Me.Top = 0
    Me.Left = 0
    
    server = GetSetting(App.EXEName, "x", "server")
    port = GetSetting(App.EXEName, "x", "port")
    userID = GetSetting(App.EXEName, "x", "uid")
    password = GetSetting(App.EXEName, "x", "password")
    
    txtServer.Text = server
    txtPort.Text = port
    txtUserID.Text = userID
    txtPassword.Text = password
    Exit Sub
    errhandler:
        MsgBox "Terdapat kesalahan pada program!!!", vbCritical
        Me.Hide
    End Sub
    

Contoh kode program koneksi vb ke mysql
Option Explicit
'----------------------------------------------------
'Start Connecting database mysql variable declaration
Public cn As New ADODB.Connection
Private rs As New ADODB.Recordset
Public server, port, userID, password As String
'End Connecting database mysql variable declaration
'----------------------------------------------------

Public Sub connect()
If cn.State = adStateOpen Then
    cn.Close
End If
server = GetSetting(App.EXEName, "x", "server")
port = GetSetting(App.EXEName, "x", "port")
userID = GetSetting(App.EXEName, "x", "uid")
password = GetSetting(App.EXEName, "x", "password")

cn.Open "Driver=mysql odbc 3.51 driver;server=" & server & ";uid=" & userID & ";password=" & password & ";port=" & port & ";database=supervisi"
induk.Toolbar1.Buttons(2).Enabled = True
Exit Sub
errhandler:
    induk.Show
    induk.Toolbar1.Buttons(2).Enabled = False
End Sub

0 komentar:

Posting Komentar

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Justin Bieber, Gold Price in India