目標:連接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 msgbox "連接數據庫失敗" 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)
'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
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 "導入完成"