'在使用前需要先安装MySql的驱动,进行正确配置
'注意:必须给出正确的服务器名、数据库名、表名、数据库连接的用户名、密码
Option Explicit
Dim Cnn As ADODB.Connection '定义ADO连接对象
Dim Records As ADODB.Recordset '定义ADO记录集对象
'连接到数据库
Function CnnOpen(ByVal ServerName As String, ByVal DBName As String, ByVal TblName As String, ByVal User As String, ByVal PWD As String) '服务器名或IP、数据库名、登录用户、密码
Dim CnnStr As String '定义连接字符串
Set Cnn = CreateObject("ADODB.Connection") '创建ADO连接对象
Cnn.CommandTimeout = 15 '设置超时时间
CnnStr = "DRIVER={MySql ODBC 5.1 Driver};SERVER=" & ServerName & ";Database=" & DBName & ";Uid=" & User & ";Pwd=" & PWD & ";Stmt=set names GBK" '
Cnn.ConnectionString = CnnStr
Cnn.Open
End Function
'关闭连接
Function CnnClose()
If Cnn.State = 1 Then
Cnn.Close
End If
End Function
'把Excel写入MySql中的数据库
Function InsertToMySql(ByVal SheetName As String, ByVal TblName As String)
Dim SqlStr As String
Dim i, j As Integer
Dim Columns, Rows As Integer
Columns = VBAProject.func_public.GetTotalColumns(SheetName)
Rows = VBAProject.func_public.GetTotalRows(SheetName)
Set Records = CreateObject("ADODB.recordset")
'取得结果集并插入数据到数据库
Set Records = CreateObject("ADODB.Recordset")
'以下语句提供了插入思路,我只是把单条记录的插入方式改为循环,以把所有的记录添加到表中
'rs.Open "insert into newtable values('" & ActiveSheet.Cells(i, 1).Value & "'," & "'" & ActiveSheet.Cells(i, 2).Value & "')", cnn, 0
For i = 2 To Rows
SqlStr = "INSERT INTO " & TblName & " values('" & Sheets(SheetName).Cells(i, 1).Value & "'" '注意:" values('",字母“v”之前是有空格的!!!
For j = 2 To Columns
SqlStr = SqlStr & ",'" & Sheets(SheetName).Cells(i, j).Value & "'"
Next
SqlStr = SqlStr & ")"
Set Records = Cnn.Execute(SqlStr) 'rs.Open SqlStr, cnn, 0 不能用这条语句实现!!!
Next
MsgBox "Insert!", vbOKOnly, "Excel To MySql"
End Function
'清除对象
Function ClearObj()
Set Cnn = Nothing
Set Records = Nothing
End Function
温馨提示:内容为网友见解,仅供参考