我正在尝试使用 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
提交
取消