我有一個(gè)使用 sqlalchemy 的方法 def insert_amended_values(self, data): insert_stmt = """INSERT INTO amended (date, volume, price, updated) VALUES (%(date)s, %(volume)s, %(price)s, %(updated)s);""" crsr = self.connection.engine.raw_connection().cursor() crsr.executemany(insert_stmt, data)其中需要的數(shù)據(jù)是字典列表,例如[ {'date': '2020-06-27', 'volume': '30', 'price': 50, 'updated': '2020-10-21 17:17:50'}, {'date': '2020-06-28', 'volume': '32', 'price': 48, 'updated': '2020-10-21 17:17:50'}, {'date': '2020-06-29', 'volume': '26', 'price': 56, 'updated': '2020-10-21 17:17:50'}]但我得到了錯(cuò)誤TypeError: ('Params must be in a list, tuple, or Row', 'HY000')如何將字典列表轉(zhuǎn)換為列表或行列表,同時(shí)保留參數(shù)化查詢?
1 回答

慕妹3242003
TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
將數(shù)據(jù)保留在listof中dict,將 SQL 語句包裝在 SQLAlchemytext對象中并使用:name參數(shù)樣式
import sqlalchemy as sa
# …
def insert_amended_values(self, data):
insert_stmt = sa.text("""INSERT INTO amended (date, volume, price, updated)
VALUES (:date, :volume, :price, :updated);""")
with self.connection.engine.begin() as conn:
conn.execute(insert_stmt, data)
添加回答
舉報(bào)
0/150
提交
取消