[英]This query runs perfectly in Access 2010 but when I try to execute it in my code I get Syntax error in INSERT INTO statement
I am a newby programmer and I have had a look at other posts similar to this and they say that the problem is usually due to reserved words being used, however I am sure that I am not using any. 我是一个新手程序员,我看过其他类似的帖子,他们说问题通常是由于使用了保留字,但我确信我没有使用任何。 The sql runs fine in access and creates the record (using the sql from the variable v_sqlquery, however when in VB the following error appears "Syntax error in INSERT INTO statement". Can anyone help me please, I have spent a few hours trying to solve this? Thanks in advance. sql在访问中运行良好并创建记录(使用变量v_sqlquery中的sql,但是在VB中出现以下错误“INSERT INTO语句中的语法错误”。任何人都可以帮助我,我花了几个小时试图解决这个问题?提前谢谢。
Dim v_SQLquery As String 'stores the sql query
Dim v_command As OleDbCommand 'passes command to db
Dim v_results As OleDbDataReader
Dim v_custID As Integer
Dim v_balance As String
Dim v_purchase As String
Dim v_date As Date
Dim v_time As Date
Dim v_transID As Integer
v_custID = txt_custID.Text
v_balance = txt_custbalance.Text
v_purchase = txt_puramount.Text
v_date = DateValue(Now) 'the current date
v_time = TimeValue(Now) 'the current time
If v_purchase = "" Then
MsgBox("Please enter the purchase amount.")
ElseIf v_purchase > v_balance Then
MsgBox("There are not enough funds in the account to complete this transaction.")
v_SQLquery = "INSERT INTO Transaction (Trans_type, Trans_amount, Trans_date, Trans_time, Cust_ID) VALUES ('P','" & v_purchase & "','" & v_date & "','" & v_time & "','" & v_custID & "');"
v_command = New OleDbCommand(v_SQLquery, v_connection)
v_results = v_command.ExecuteScalar
End If
v_connection.close()
The immediate error is because Transaction
is a reserved word . 立即错误是因为Transaction
是保留字 。 Bracket that table name in your INSERT
statement. 在INSERT
语句中为表名INSERT
。
"INSERT INTO [Transaction] (
Fixing that issue may expose other issues. 修复该问题可能会暴露其他问题。 For example Access' db engine recognizes a date enclosed in #
characters, such as #2015-02-04# , as Date/Time datatype. 例如,Access'db引擎识别#
字符所包含的日期,例如#2015-02-04# ,作为日期/时间数据类型。 But the same date enclosed in single quotes, '2015-02-04' , will be handled as a string value (which it is). 但是用单引号“2015-02-04”封装的同一日期将作为字符串值处理(它是)。 We can't tell yet whether that issue applies to your situation. 我们还不能确定这个问题是否适用于您的情况。 But there is a way to avoid such delimiter issues. 但有一种方法可以避免这种分隔符问题。
As others advised already, you would be wise to use a parameterized INSERT
instead of concatenating values into the statement text. 正如其他人所建议的那样,使用参数化INSERT
而不是将值连接到语句文本中是明智的。 Not only will that approach protect you from SQL injection, it also avoids delimiter issues for the values you're inserting. 这种方法不仅可以保护您免受SQL注入的影响,还可以避免您插入的值的分隔符问题。
Note with either approach, the reserved word issue for your table name will still apply. 请注意,无论采用哪种方法,您的表名的保留字问题仍然适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.