关于VBS连接MySQL与连接Excel_MySQL
程序员文章站
2022-05-03 17:46:11
...
目标:连接MySQL查找数据放入新建Excel表
实现过程:
1.连接数据库
首先要去MySQL官网下载个ODBC数据源。
安装之后,即可在控制面板-管理工具-ODBC数据源-添加,中看到MySQL驱动名称:
'连接数据库 StrCnn="Provider=MSDASQL.1;Persist Security Info=True;Extended Properties='Driver=MySQL ODBC 5.3 Unicode Driver;SERVER=188.1.1.132;UID=grute;PWD=grute;DATABASE=grute;PORT=3307'" Set Cnn = CreateObject("ADODB.Connection") Cnn.Open strCnn '查看是否连接成功,成功状态值为1 If Cnn.State = 0 Then msgbox "连接数据库失败" wscript.quit End If
2.连接Excel
'连接Excel dim oExcel,oWb,oSheet Set oExcel= CreateObject("Excel.Application") oexcel.Workbooks.Add()
3.输入SQL语句,从MySQL中查找数据
strQuery = "select * from test" Set rs = Cnn.Execute(strQuery)
4.把MySQL的查询结果循环放入Excel
'i为Excel行号,k为列号
Dim i i=0 arr_column = array("序号", "姓名", "用户名", "密码", "权限") If Not rs.BOF Then Do While Not rs.EOF i = i + 1 For k = 1 To 5 '循环5次 oExcel.Cells(i, k).Value = rs(arr_column(k - 1)) Next rs.MoveNext Loop Else wscript.echo "失败" End If
5.保存Excel
oexcel.ActiveWorkbook.SaveAs("C:\Users\Administrator\Desktop\test.xlsx")
6.退出
oExcel.WorkBooks.Close oExcel.Quit rs.Close Cnn.Close Set Cnn = Nothing msgbox "导入完成"
以上,
完全代码如下,要求本机安装MySQL数据源,且188.1.1.132机器上MySQL用户名为grute、密码为grute、库名为grute、表名为test、test的列名分别为(序号,姓名,用户名,密码,权限),保存为后缀名VBS即可运行。
'定义变量 Dim Cnn Dim Rst Dim strCnn Dim i i = 0 arr_column = array("序号", "姓名", "用户名", "密码", "权限") '连接数据库 StrCnn="Provider=MSDASQL.1;Persist Security Info=True;Extended Properties='Driver=MySQL ODBC 5.3 Unicode Driver;SERVER=188.1.1.132;UID=grute;PWD=grute;DATABASE=grute;PORT=3307'" Set Cnn = CreateObject("ADODB.Connection") Cnn.Open strCnn '查看是否连接成功,成功状态值为1 If Cnn.State = 0 Then msgbox "连接数据库失败" wscript.quit End If '连接Excel dim oExcel,oWb,oSheet Set oExcel= CreateObject("Excel.Application") oexcel.Workbooks.Add() '输入SQL语句 strQuery = "select * from test" Set rs = Cnn.Execute(strQuery) 'i为Excel行号,k为列号 arr_column = array("序号", "姓名", "用户名", "密码", "权限") If Not rs.BOF Then Do While Not rs.EOF i = i + 1 For k = 1 To 5 '循环5次 oExcel.Cells(i, k).Value = rs(arr_column(k - 1)) Next rs.MoveNext Loop Else wscript.echo "失败" End If oexcel.ActiveWorkbook.SaveAs("C:\Users\Administrator\Desktop\test.xlsx") oExcel.WorkBooks.Close oExcel.Quit rs.Close Cnn.Close Set Cnn = Nothing msgbox "导入完成"