1

问题是我无法创建一个名为的字段Date(我认为因为它是一种类型)有什么想法吗?

from pyodbc import connect
# database connect
conn = connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=test.mdb')
cursor = conn.cursor()
# sql query execute
query = "create table MyTable(name varchar(30), age integer , Date date)"
cursor.execute(query)
# commit changes             
conn.commit()
conn.close()

错误:

Traceback (most recent call last):
  File "\Path\to\myscript\test.py", line 9, in <module>
    cursor.execute(query)
ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in field definition. (-3553) (SQLExecDirectW)')

环境:Windows 7 64bit,Python 2.7 pyodbc-3.0.6.win-amd64-py2.7

4

3 回答 3

5

DATE是 Access(和其他软件)中的保留字

尝试Date用方括号将列名括[]起来,或者更好的是,想出一个不同的列名。

...
query = "create table MyTable(name varchar(30), age integer , [Date] date)"
...
于 2013-01-15T19:19:23.613 回答
3

用 ` 符号将反引号中的名称括起来。但是,我强烈建议将名称更改为其他名称,以防止发生拼写错误。

于 2013-01-15T19:18:01.750 回答
1

You're right, you can't create a column with the same name as type. Some RDBMS's will allow you to do this if you quote it, i.e. "..age integer, "Date" date)" (or as others have said, backticks or square brackets) but then you have to quote it in all your queries as well. Better to avoid that.

Note that this isn't a python problem, it's a problem with the database server (which appears to be MS Access). (And to be accurate, it's not a problem with the database server, that's just how it works. It just has nothing to do with python.)

于 2013-01-15T19:20:09.837 回答