Access 是一款常用的關(guān)系數(shù)據(jù)庫管理系統(tǒng),但是它的穩(wěn)定性和性能都不是很好。因此,很多開發(fā)者選擇將 Access 的數(shù)據(jù)導(dǎo)出到 MySQL 數(shù)據(jù)庫中,以便更好地管理和使用數(shù)據(jù)。下面是使用 VBA 代碼將 Access 中的數(shù)據(jù)導(dǎo)出到 MySQL 數(shù)據(jù)庫的步驟:
'1. 引用 MySQL ActiveX Connector
Option Explicit
Private conMySQL As New ADODB.Connection
Private Sub ConnectToMySQL()
'MySQL 配置信息
Dim server As String
Dim port As String
Dim db As String
Dim user As String
Dim password As String
'連接 MySQL 數(shù)據(jù)庫
server = "localhost"
port = "3306"
db = "test"
user = "root"
password = "root"
conMySQL.ConnectionString = "DRIVER={MySQL ODBC 8.0 Unicode Driver};" _
& "SERVER=" & server & ";" _
& "PORT=" & port & ";" _
& "DATABASE=" & db & ";" _
& "USER=" & user & ";" _
& "PASSWORD=" & password & ";"
conMySQL.Open
End Sub
Private Sub ExportToMySQL()
Dim rstAccess As Recordset
Dim rstMySQL As Recordset
Dim strSql As String
Dim strFields As String
Dim strValues As String
Set rstAccess = CurrentDb.OpenRecordset("SELECT * FROM tblAccess")
'連接 MySQL 數(shù)據(jù)庫
ConnectToMySQL
If Not rstAccess.EOF Then
rstAccess.MoveFirst
Do Until rstAccess.EOF
strFields = ""
strValues = ""
'生成 SQL 插入語句
For i = 0 To rstAccess.Fields.Count - 1
strFields = strFields & rstAccess.Fields(i).Name & ", "
strValues = strValues & "'" & rstAccess.Fields(i).Value & "', "
Next i
strFields = Left(strFields, Len(strFields) - 2)
strValues = Left(strValues, Len(strValues) - 2)
strSql = "INSERT INTO tblMySQL ([" & strFields & "]) VALUES (" & strValues & ")"
'執(zhí)行插入 SQL 語句
Set rstMySQL = conMySQL.Execute(strSql)
rstAccess.MoveNext
Loop
End If
MsgBox "數(shù)據(jù)導(dǎo)出完成!"
rstAccess.Close
Set rstAccess = Nothing
rstMySQL.Close
Set rstMySQL = Nothing
conMySQL.Close
End Sub
通過以上 VBA 代碼,我們可以將 Access 中的數(shù)據(jù)導(dǎo)出到 MySQL 數(shù)據(jù)庫中,實現(xiàn)更好的數(shù)據(jù)管理和使用。