Matt Owens
Matt Owens

Reputation: 23

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. 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"))

Upvotes: 2

Views: 6575

Answers (2)

Air
Air

Reputation: 8595

The syntax error is in your 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. In Access SQL, as in SQL Server, the delimiters used are square brackets; 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. See also: SQL standard to escape column names?

Upvotes: 2

Bryan
Bryan

Reputation: 17693

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).

Upvotes: 4

Related Questions