Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用vba将excel数据导入mysql数据库_Mysql_Vba - Fatal编程技术网

使用vba将excel数据导入mysql数据库

使用vba将excel数据导入mysql数据库,mysql,vba,Mysql,Vba,我正在尝试将数据导入MySQL数据库,我已经搜索了许多示例和解决方案,但都不起作用,我也不知道为什么。下面是我的vba代码。我收到运行时错误2147217900(80040e14),表示您的sql语法有错误;检查与您的MySQL对应的手册,以了解在“='41282'附近使用的正确语法 Sub Getdata() Dim conn As New ADODB.Connection Dim server_name As String Dim database_name As String Dim us

我正在尝试将数据导入MySQL数据库,我已经搜索了许多示例和解决方案,但都不起作用,我也不知道为什么。下面是我的vba代码。我收到运行时错误2147217900(80040e14),表示您的sql语法有错误;检查与您的MySQL对应的手册,以了解在“='41282'附近使用的正确语法

Sub Getdata()
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String

Dim a As Long ' counter
Dim i As Long, j As Variant, k As Long
Dim sqlstr As String ' SQL to perform various actions
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim field3 As String
Dim rs As ADODB.Recordset

sqlstr = "INSERT INTO" & table1 & "SET" _
& field1 & " = '" & i & "', " _
& field2 & " = '" & j & "', " _
& field3 & " = '" & k & "'"
conn.Execute sqlstr
Next a
End With
skipwrite:
End Sub

Excel中的日期存储为1899-12-31和实际日期之间的天数。您要做的是将数字存储在具有数字格式的字段中

41282是天数。所以你应该计算如下:

'1899-12-31' + 'i days'

以mysql格式获取日期(默认为YYYY-MM-DD)。我不知道VBA要获得这个结果需要什么样的字符串操作命令,但在MYSQL端,这应该可以修复您的错误

,只需在连接的字符串中划掉表名和
SET
命令。此外,由于列名中使用了保留字,所以在前后添加勾号(顺便说一下,作为最佳做法,应避免使用保留字):


同样如@Lelio所述,将日期格式化以正确读取到MySQL
date
列中。

输出您创建的
sqlstr
,您将看到缺少一些空格:
插入tempmaxset
sqlstr = "INSERT INTO " & table1 & " SET " _
            & "`" & field1 & "` = '" & Format(i, "YYYY-MM-DD") & "', " _
            & "`" & field2 & "` = '" & j & "', " _
            & "`" & field3 & "` = '" & k & "';"