Python+Sqlite3,如何使用"index"更新表



使用索引访问数据库时提示错误。

我认为'index'是不可用的sql查询'WHERE index =?'

如何使用索引列更新数据库?

sqlite3.OperationalError: near "index": syntax error

import pandas as pd
import sqlite3

# Create DB file
con = sqlite3.connect("./tester.db")
data = {'date': ['20210210', '20210209'], 'value': [15, 17]}
df_add = pd.DataFrame(data, columns=['value'], index=data['date'])
df_add.to_sql('placeA', con, if_exists='replace')
con.close()
# Update DB using index
con = sqlite3.connect("./tester.db")
cur = con.cursor()
cur.execute("UPDATE placeA SET value = ? WHERE index = ?", (232, "20210210"))
con.commit()
cur.execute("SELECT * FROM placeA")
f = cur.fetchall()
print(f)

如果sql文件中的列名为'index',则无法正常工作。

所以我通过将'index'列重命名为'date'来解决问题。

但是我需要保持列名'index',所以我在…之后再次更改了它。

cur.execute("ALTER TABLE placeA RENAME COLUMN 'index' to date")
...
cur.execute("ALTER TABLE placeA RENAME COLUMN date to 'index'")

最新更新