sqlite3.OperationalError:靠近“index”:语法错误

4 python sqlite

我正在尝试使用 sqlite3 模块使用 python 连接到数据库,但出现错误 - sqlite3.OperationalError: close "index": 语法错误


我为此搜索了一些解决方案,但没有得到解决方案。我是 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()
Run Code Online (Sandbox Code Playgroud)

帮助我摆脱这个错误:(

Tre*_*edJ 6

INDEX是SQLite3中的一个关键字。因此,它将被解析为关键字。不过,有几种方法可以解决这个问题。

根据文档,您可以使用反引号或引号将其指定为表名称。例如,

CREATE TABLE IF NOT EXISTS `index` ...
Run Code Online (Sandbox Code Playgroud)

或者

CREATE TABLE IF NOT EXISTS "index" ...
Run Code Online (Sandbox Code Playgroud)

可能有效。

您可以从命令将参数传递给 sql 语句execute()。因此,

create = r'''CREATE TABLE ... VALUES(?,?,?,?);'''  # use ? for placeholders
c.execute(create, (url, title, description, keywords))  # pass args as tuple
Run Code Online (Sandbox Code Playgroud)

与直接使用 Python 格式化参数相比,这更安全。

另请注意,SQLite 的 autoinc 语法AUTOINCREMENT不带下划线,并且要求该字段也是INTEGER PRIMARY KEY.