我正在嘗試使用 sqlite3 模塊使用 python 連接到數據庫,但出現錯誤 - sqlite3.OperationalError: near "index": syntax error我為此搜索了一些解決方案,但沒有得到解決方案。我是 sqlite3 的新手def insert_into_db(url, title, description, keywords): con = sqlite3.connect('index.db') c = con.cursor() create = r'''CREATE TABLE IF NOT EXISTS index (id INTEGER NOT NULL AUTO_INCREMENT,url VARCHAR,description TEXT,keywords TEXT);INSERT INTO index(url, title, description, keywords)VALUES('{}','{}',{}','{}');'''.format(url, title,description, keywords) c.execute(create) con.commit() con.close()
2 回答

烙印99
TA貢獻1829條經驗 獲得超13個贊
INDEX是 SQLite3 中的關鍵字。因此,它將被解析為關鍵字。不過,有幾種方法可以解決這個問題。
根據文檔,您可以使用反引號或引號將其指定為表名。例如,
CREATE TABLE IF NOT EXISTS `index` ...
或者
CREATE TABLE IF NOT EXISTS "index" ...
可能工作。
您可以將參數從execute()命令傳遞給您的 sql 語句。因此,
create = r'''CREATE TABLE ... VALUES(?,?,?,?);''' # use ? for placeholders
c.execute(create, (url, title, description, keywords)) # pass args as tuple
與直接使用 Python 格式化參數相比,這更安全。
另請注意,SQLite 的 autoinc 語法AUTOINCREMENT沒有下劃線,并且它們要求該字段也是INTEGER PRIMARY KEY.
添加回答
舉報
0/150
提交
取消