欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

excel自動導入mysql數據庫

劉姿婷2年前10瀏覽0評論

Excel自動導入MySQL數據庫可以大大提高工作效率,避免手動導入出錯和重復勞動。下面介紹如何通過VBA編寫自動導入代碼。

Sub importData()
Dim strPath As String, strConn As String
Dim strQuery As String, strSQL As String
Dim cn As Object, rs As Object
Dim row As Integer, col As Integer
'設置Excel表格路徑
strPath = ThisWorkbook.Path & "\data.xlsx"
'設置MySQL連接
strConn = "Provider=MSDASQL.1;Password=xxx;Persist Security Info=True;User ID=root;Initial Catalog=test;Data Source=localhost"
'設置SQL語句
strQuery = "SELECT * FROM data"
'連接MySQL數據庫
Set cn = CreateObject("ADODB.Connection")
cn.Open (strConn)
'執行SQL查詢
Set rs = CreateObject("ADODB.Recordset")
rs.Open strQuery, cn, 2, 2
'遍歷Excel表格
For row = 2 To 100 '假設數據在第2行到第100行
'組合SQL語句
strSQL = "INSERT INTO data (col1, col2, col3) VALUES ("
For col = 1 To 3 '假設數據有3列
strSQL = strSQL & "'" & ActiveSheet.Cells(row, col).Value & "'"
If col < 3 Then strSQL = strSQL & ","
Next col
strSQL = strSQL & ")"
'執行SQL語句
rs.AddNew
For i = 0 To rs.Fields.Count - 1
rs.Fields(i).Value = ActiveSheet.Cells(row, col).Value
Next i
rs.Update
Next row
'關閉數據庫連接
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

通過以上代碼,我們可以實現將Excel表格中的數據自動導入到MySQL數據庫中的data表中。