首先需要在项目中,引用-Microsoft ActiveX Data Objects 2.5 Library
然后就可以连接和记录集对象了
使用ADODB.Connection进行连接,使用RemoteCn.Execute方法进行增、删、改操作。使用ADODB.Recordset进行查操作,当然也可以使用它的UpdateBatch方法进行修改。
'建立远程数据库连接
Public Sub IniRemoteCn()
On Error GoTo ErrDeal:
If RemoteCn.State = adStateOpen Then RemoteCn.Close
Dim db_host As String
Dim db_port As String
Dim db_user As String
Dim db_pass As String
Dim db_data As String
Dim strCn As String
db_host = GetSetting(SaveKey, "RemoteCn", "host", "192.168.1.1")
db_port = GetSetting(SaveKey, "RemoteCn", "port", "3306")
db_user = GetSetting(SaveKey, "RemoteCn", "user", "root")
db_pass = GetSetting(SaveKey, "RemoteCn", "pass", "1234")
db_data = GetSetting(SaveKey, "RemoteCn", "data", "persons")
strCn = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=" & db_host & ";" & _
"PORT=" & db_port & ";" & _
"DATABASE=" & db_data & ";" & _
"UID=" & db_user & ";" & _
"PWD=" & db_pass & ";" & _
"OPTION=3;stmt=SET NAMES GB2312"
With RemoteCn
.ConnectionTimeout = 2
.ConnectionString = strCn
.Mode = adModeReadWrite
.Open
End With
SaveSetting SaveKey, "RemoteCn", "Enable", "True"
Exit Sub
ErrDeal:
SaveSetting SaveKey, "RemoteCn", "Enable", "Flase"
End Sub
注意:进行Insert SQL语句的编写时候,VarChar字段和日期字段要用单引号,关键字和字段之间要有空格,指定字段名的情况下,字段数和插入的数值个数相同,否则报错Columns不相等。