[英]Syntax error when inserting into Access 2013 with Pyodbc
I am using Pyodbc and am trying to insert values into a Microsoft 2013 Access Database. 我正在使用Pyodbc,并尝试将值插入Microsoft 2013 Access数据库。 However, everytime I run the code I get an error on the execute line: 但是,每次我运行代码时,在执行行上都会出现错误:
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement. (-3502) (SQLExecDirectW)')
Does anyone have any ideas how to fix this? 有谁知道如何解决这个问题? I have put my code below. 我把我的代码放在下面。
conn = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Database2.accdb;")
cur=conn.cursor()
sql="""INSERT INTO Invoices (LINE TYPE,INVOICE NUMBER) VALUES (?,?)"""
cur.execute(sql,("Line","41243"))
Columns with spaces in the name need to be surrounded with brackets: 名称中带有空格的列需要用方括号括起来:
sql="""INSERT INTO Invoices ([LINE TYPE],[INVOICE NUMBER]) VALUES (?,?)"""
If you have control over the table design, I'd consider removing the spaces from the column names, replacing them with underscores ( LINE_TYPE
) or using pascal case ( LineType
). 如果您可以控制表设计,则可以考虑从列名中删除空格,将其替换为下划线( LINE_TYPE
)或使用pascal大小写( LineType
)。
The syntax error is in your SQL: 语法错误在您的SQL中:
INSERT INTO Invoices (LINE TYPE,INVOICE NUMBER) VALUES (?,?)
I've yet to encounter a DBMS that allows you to reference columns whose names contain spaces without specially delimiting the column name. 我还没有遇到过DBMS,该DBMS允许您引用名称中包含空格的列,而无需专门定界列名称。 In Access SQL, as in SQL Server , the delimiters used are square brackets; 在Access SQL中, 就像在SQL Server中一样 ,使用的定界符是方括号。 so you would have to write: 所以你必须写:
INSERT INTO Invoices ([LINE TYPE], [INVOICE NUMBER]) VALUES (?,?)
The SQL standard uses double quotes, but most vendors aren't particularly bothered about conforming to the standard. SQL标准使用双引号,但是大多数供应商对遵循该标准并不特别烦恼。 See also: SQL standard to escape column names? 另请参见: SQL标准是否转义列名?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.