【问题标题】:Python+Sqlite3, how to update table using "index"Python+Sqlite3,如何使用“索引”更新表
【发布时间】:2021-02-10 00:52:57
【问题描述】:

使用索引访问数据库时弹出错误。

我认为 '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)

【问题讨论】:

  • 我想这可能是使用“cur.execute("ALTER TABLE placeA RENAME COLUMN 'index' to date")”更改索引列名称的解决方案,但我仍然不确定为什么'index ' 不起作用。

标签: python sqlite indexing where-clause using


【解决方案1】:

如果sql文件中名为'index'的列不知何故无法正常工作。

所以我通过将“索引”列重命名为“日期”来解决这个问题。

但我需要保留列名“索引”,所以之后我再次更改了它..

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

【讨论】:

    猜你喜欢
    • 2014-06-27
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    相关资源
    最近更新 更多