Coding4ever’s Blog

Just coding… coding… and coding… because coding should be fun :)

Membuat Fungsi Koneksi Untuk Beberapa Database (Firebird, MySQL, Ms SQL Server Dan Ms Access)

| Comments

1. Tambahkan sebuah modul dan copy paste kode berikut :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Public conn As ADODB.Connection

Public Enum TIPE_DATABASE
   FIREBIRD = 1
   MYSQL = 2
   SQLSERVER = 3
   MSACCESS = 4
End Enum

Public Function connToDB(ByVal tipeDb As TIPE_DATABASE, Optional ByVal serverName As String = "", _
   Optional ByVal userName As String = "", Optional ByVal userPass As String = "", _
   Optional ByVal dbPath As String = "", Optional ByVal dbName As String = "") As Boolean

   Dim strCon As String

   On Error GoTo errHandle

   Select Case tipeDb
      Case FIREBIRD
         strCon = "DRIVER=Firebird/Interbase(r) Driver;UID=" & userName & ";PWD=" & userPass & ";" & _
         "DBNAME=" & serverName & ":" & dbPath & "\" & dbName & ""

      Case MYSQL
         strCon = "DRIVER={MySQL ODBC 5.1 Driver};SERVER=" & serverName & ";DATABASE=" & dbName & ";" & _
         "UID=" & userName & ";PWD=" & userPass & ";OPTION=3"

      Case SQLSERVER
         strCon = "Provider=SQLOLEDB.1;User ID=" & userName & ";Pwd=" & userPass & ";" & _
         "Initial Catalog=" & dbName & ";Data Source=" & serverName & ""

      Case MSACCESS
        If Len(userPass) > 0 Then
           strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & dbPath & "\" & dbName & ";" & _
           "Jet OLEDB:Database Password=" & userPass & ""
        Else
           strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & dbPath & "\" & dbName & ""
        End If
   End Select

   Set conn = New ADODB.Connection
   conn.ConnectionString = strCon
   conn.Open

   connToDB = True

   Exit Function
errHandle:
   connToDB = False
End Function

2. Pada form tambahkan sebuah objek command dan set properties Name = cmdTesKoneksi

copy paste kode berikut :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Private Sub cmdTesKoneksi_Click()
   Dim result  As Boolean

   'Firebird
   result = connToDB(FIREBIRD, "127.0.0.1", "SYSDBA", "masterkey", "d:\data", "db_akademik.fdb")
   Debug.Print result

   'MySQL
   result = connToDB(MYSQL, "127.0.0.1", "root", "masterkey", , "db_akademik")
   Debug.Print result

   'SQL Server 2000
   result = connToDB(SQLSERVER, "127.0.0.1", "sa", "masterkey", , "db_akademik")
   Debug.Print result

   'Ms Access - tanpa password
   result = connToDB(MSACCESS, , , , "d:\data", "db_akademik.mdb")
   Debug.Print result

   'Ms Access - menggunakan password
   result = connToDB(MSACCESS, , , "masterkey", "d:\data", "db_akademik.mdb")
   Debug.Print result
End Sub

Untuk nilai semua parameter fungsi connToDB disesuaikan dengan kondisi komputer Anda. Selamat mencoba :)

Comments