Sqlite 3 Python操作错误:sqlite3.OperationalError创建表

时间:2017-05-15 08:50:53

标签: python sql python-3.x sqlite

import sqlite3

conn=sqlite3.connect('food.db')
print("Opened Database Successfully")

conn.execute('''CREATE TABLE ORDER
        (ORDERID INT PRIMARY KEY NOT NULL,
        FOODID INT NOT NULL,
        CUSTOMERID INT NOT NULL,
        DATEOFORDER CHAR(9) NOT NULL,
        PRICEOFORDER REAL NOT NULL,
            FOREIGN KEY (CUSTOMERID) REFERENCES CUSTOMER(CUSTID),
            FOREIGN KEY (FOODID) REFERENCES FOOD(FOODID));''')

conn.close()

创建此代码,我收到错误消息作为操作错误。

Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
sqlite3.OperationalError: near "ORDER": syntax error

已创建客户和食品表,它们都有效

1 个答案:

答案 0 :(得分:0)

ORDER是SQL中的保留字,您需要引用它才能将其用作表名。将它放在双引号中

conn.execute('''CREATE TABLE "ORDER"
        (ORDERID INT PRIMARY KEY NOT NULL,
        FOODID INT NOT NULL,
        CUSTOMERID INT NOT NULL,
        DATEOFORDER CHAR(9) NOT NULL,
        PRICEOFORDER REAL NOT NULL,
            FOREIGN KEY (CUSTOMERID) REFERENCES CUSTOMER(CUSTID),
            FOREIGN KEY (FOODID) REFERENCES FOOD(FOODID));''')

您也可以使用[ORDER]`ORDER`,但这些使用非标准语法。

请参阅SQLite keywords documentation