将ID,时间戳和字符串插入Access数据库时出现语法错误

时间:2014-07-01 16:38:08

标签: sql ms-access syntax vbscript

有人可以告诉我为什么这段代码会抛出语法错误? :

commText = "INSERT INTO Messages VALUES (" & (recordsQty + 1) & "," & currentUserID & ",#" & Now & "#, '" & messageText & "')"
conn.Open connStr
conn.Execute commText
conn.Close()

我插入的表格如下:

ID Number PK
userID Number FK
messageDate Date/Time
messageText Text

最后,代码抛出了这个错误:

Script error detected at line 20.
Source line: conn.execute commText
Description: Syntax error in INSERT INTO statement.

提前致谢!

4 个答案:

答案 0 :(得分:1)

如果您的ID字段设置为自动增量,则无需在where子句中指定它。

commText = "INSERT INTO Messages VALUES (" & currentUserID & ",#" & Now & "#, '" & messageText & "')"

此外,您还需要确保外键表中存在currentUserID

答案 1 :(得分:1)

commText = "INSERT INTO Messages (userID, messageDate, messageText) " & _
           "VALUES (" & currentUserID & ", #" & Now & "#, '" & messageText & "')"

或者,如果您的主键不是自动增量:

commText = "INSERT INTO Messages (ID, userID, messageDate, messageText) " & _
           "VALUES (" & (recordsQty + 1) & ", "  & currentUserID & ", #" & Now & "#, '" & messageText & "')"

答案 2 :(得分:1)

Swagata是正确的,您不需要指定自动列,但是如果它们与您正在完全插入结构的表不匹配,则需要明确指定列。

commText = "INSERT INTO Messages (UserId, messageDate, messageText  ) VALUES (" & currentUserID & ",#" & Now & "#, '" & messageText & "')"

答案 3 :(得分:1)

尝试用单引号替换您的主题标签。

commText = "INSERT INTO Messages VALUES (" & (recordsQty + 1) & "," & currentUserID & ",'" & Now & "', '" & messageText & "')"