目标:连接MySQL查找数据放入新建Excel表
实现过程:
首先要去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 <span style="white-space:pre"> </span>msgbox "连接数据库失败" <span style="white-space:pre"> </span>wscript.quit End If
'连接Excel dim oExcel,oWb,oSheet Set oExcel= CreateObject("Excel.Application") oexcel.Workbooks.Add()
strQuery = "select * from test" Set rs = Cnn.Execute(strQuery)
<pre name="code" class="vb"><pre name="code" class="vb">'i为Excel行号,k为列号 <pre name="code" class="vb">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
oexcel.ActiveWorkbook.SaveAs("C:\Users\Administrator\Desktop\test.xlsx")
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 "导入完成"
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/tiantuanzi/article/details/48048813