You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA向MySQL插入数据报错-2147217900:未知列'Automated'

解决VBA向MySQL推送数据时的"Unknown column"错误

问题根源

看你的错误提示和代码片段,问题出在第四列数据的SQL拼接细节上:
你给前三个字段的值都用单引号(')包裹了,但第四列Experiment_condition对应的esc(.Cells(rowCursor, 4))没有加单引号。当值是Automated这种字符串时,MySQL会把它误识别成列名,而不是你要插入的字符串值,所以抛出了"Unknown column 'Automated' in 'field list'"的错误。

修复后的代码

只需要给第四列的值也补上单引号就行,修改后的SQL拼接部分如下:

With wsBooks
For rowCursor = 2 To 3
strSQL = "INSERT INTO TestExperiment (Experiment_Name, Experiment_Method, Experiment_Analyst, Experiment_condition) " & _
"VALUES ('" & esc(.Cells(rowCursor, 1)) & "', " & _
"'" & esc(.Cells(rowCursor, 2)) & "', " & _
"'" & esc(.Cells(rowCursor, 3)) & "', " & _
"'" & esc(.Cells(rowCursor, 4)) & "')" ' 这里补上缺失的单引号
oConn.Execute strSQL
Next
End With

更安全的优化建议

虽然补单引号能解决当前问题,但直接拼接字符串的方式存在SQL注入风险,而且如果字段值里包含单引号(比如O'Neil),还是会触发语法错误。更可靠的方式是使用参数化查询,示例如下:

With wsBooks
For rowCursor = 2 To 3
    Dim cmd As Object
    Set cmd = CreateObject("ADODB.Command")
    cmd.ActiveConnection = oConn
    cmd.CommandText = "INSERT INTO TestExperiment (Experiment_Name, Experiment_Method, Experiment_Analyst, Experiment_condition) " & _
                      "VALUES (?, ?, ?, ?)"
    
    ' 依次添加参数(替换对应字段类型和长度)
    cmd.Parameters.Append cmd.CreateParameter(, 200, 1, 255, .Cells(rowCursor, 1).Value) ' adVarChar=200, adParamInput=1
    cmd.Parameters.Append cmd.CreateParameter(, 200, 1, 255, .Cells(rowCursor, 2).Value)
    cmd.Parameters.Append cmd.CreateParameter(, 200, 1, 255, .Cells(rowCursor, 3).Value)
    cmd.Parameters.Append cmd.CreateParameter(, 200, 1, 255, .Cells(rowCursor, 4).Value)
    
    cmd.Execute
    Set cmd = Nothing
Next
End With

如果你的项目引用了ADO库,也可以直接使用adVarChar、adParamInput这些常量,代码可读性会更好。

内容的提问来源于stack exchange,提问作者Rupesh Ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:33:05