虽然存储了直接值,但我无法将变量用作表的值。 我得到错误为“INSERT INTO语句中的语法错误。我如何克服这个错误?
sDBPAth = App.Path & "\SETMDBPATH.mdb"
sConStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sDBPAth & ";" & _
"Jet OLEDB:Engine Type=4;"
' Type=4 to create an Access97 mdb, If omitted Access2000 mdb
' ------------------------
' Create New ADOX Object
' ------------------------
Set oDB = New ADOX.Catalog
oDB.Create sConStr
Set oCn = New ADODB.Connection
oCn.ConnectionString = sConStr
oCn.Open
Set oCM = New ADODB.Command
oCM.ActiveConnection = oCn
oCM.CommandText = "CREATE TABLE MDBPATH(" & _
"MDBPATH TEXT(40) NOT NULL," & _
"pass TEXT(10))"
oCM.Execute
' Populate the table.
oCn.Execute "INSERT INTO MDBPATH VALUES (sDBPAth, 1,)" 'If 'sDBPath' is used the word sDBPath is stored not the variable value
'
' ------------------------
' Release / Destroy Objects
' ------------------------
If Not oCM Is Nothing Then Set oCM = Nothing
If Not oCn Is Nothing Then Set oCn = Nothing
If Not oDB Is Nothing Then Set oDB = Nothing
End Sub
答案 0 :(得分:2)
尝试
' Populate the table.
oCn.Execute "INSERT INTO MDBPATH VALUES ('" & sDBPAth & "', 1)"
最后你有一个额外的逗号,你需要在字符串外面传递变量。
在这种情况下你是相对保存的,因为你没有传递用户输入,但是如果你继续构建上面的INSERT语句,你将容易受到SQL Injection attacks.的攻击
答案 1 :(得分:1)
您需要在字符串之外调用变量。
oCn.Execute "INSERT INTO MDBPATH VALUES ('" & sDBPAth & "', 1)"
答案 2 :(得分:1)
您需要修改SQL语句以允许应用程序替换sDBPath值
' Populate the table.
oCn.Execute "INSERT INTO MDBPATH VALUES ('" & sDBPAth & "', 1)"
答案 3 :(得分:0)
如果sDBPAth
是实际的VB变量,则需要使用以下内容:
oCn.Execute "INSERT INTO MDBPATH VALUES ('" & sDBPAth & "', '1')"
这样insert
语句是从变量的值而不是固定字符串构造的。
此外,您的语句中似乎有一个多余的逗号,因为它们都是text
类型,您可能需要围绕这两个值的引号。