当试图将python字典列表转换为SQLite表时,我总是遇到错误



我正试图使用下面的代码将python字典列表转换为SQLite表。

conn = sqlite3.connect('stockData.db')
c = conn.cursor()
c.executemany(f"INSERT INTO AAPL1M2021 (time,open,high,low,close,volume) VALUES (%(t)s,%(o)s,%(h)s,%(l)s,%(c)s,%(v)s)", data)

每当我运行此代码时,它都会返回以下错误。

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-7-dce4eb1e6f6f> in <module>
      2 conn = sqlite3.connect('stockData.db')
      3 c = conn.cursor()
----> 4 c.executemany("INSERT INTO AAPL1M2021 (time,open,high,low,close,volume) VALUES (%(t)s,%(o)s,%(h)s,%(l)s,%(c)s,%(v)s)", data)
OperationalError: near "%": syntax error

我一定是错过了什么,因为我似乎找不到解决办法。

这是词典列表中的一本词典样本。

{'v': 26666,
  'vw': 133.233,
  'o': 133.31,
  'c': 133.49,
  'h': 133.49,
  'l': 133.02,
  't': 1609750800000,
  'n': 87}

Python的sqlite包不使用%s样式的格式。它使用?作为位置占位符,使用:name作为关键字占位符。

所以你的查询可能看起来像

c.execute(
    "INSERT INTO AAPL1M2021 (time,open,high,low,close,volume) VALUES (:t, :o, :h, :l, :c, :v)", 
    data
)

注意,executemany用于执行多个查询的参数列表。对于单个dict,请使用execute;使用executemany作为dict列表。

最新更新