使用Python元组列表在DB中插入多行

时间:2016-05-05 19:42:10

标签: python sql tuples

我有一个元组列表:

list_ = [(1,7,3000),(1,8,3500), (1,9,3900)]

我想更新一个具有给定ID的多行/值的表(在这种情况下ID = 1)

所以:

INSERT INTO table (ID, Speed, Power) VALUES (1,7,3000),(1,8,3500),(1,9,3900)

我遇到了这种格式的问题 - 我已经把字符串搞得像这样了:

INSERT INTO ... VALUES ((1,7,3000),(1,8,3500),(1,9,3900))

但是当然这不起作用,因为元组周围有额外的括号。有什么想法构建一种“pythonically”的方法吗?

2 个答案:

答案 0 :(得分:6)

嗯,你需要构建一行:

INSERT INTO ... VALUES (1,7,3000), (1,8,3500), (1,9,3900)

尝试一下:

rows = [(1,7,3000), (1,8,3500), (1,9,3900)]
values = ', '.join(map(str, rows))
sql = "INSERT INTO ... VALUES {}".format(values)

答案 1 :(得分:1)

在Python中处理此问题的惯用方式是使用所使用的数据库驱动程序提供的executemany中的cursor方法。

例如,对于使用标准库中的sqlite3模块的sqlite

conn = sqlite3.connect('/path/to/file.db')
cursor = conn.cursor()
sql = """INSERT INTO mytable (ID, Speed, Power) VALUES (?, ?, ?)"""
values = [(1,7,3000),(1,8,3500),(1,9,3900)]
cursor.executemany(stmt, values)

VALUES子句中使用的占位符因特定驱动程序而异。正确的值可以在驱动程序的文档中找到,也可以通过查找驱动程序模块的paramstyle属性来找到。

使用这种方法代替字符串插值/格式化或f字符串可确保正确引用值,从而防止SQL注入和其他错误:

>>> conn = sqlite3.connect(':memory:')
>>> cur = conn.cursor()
>>> date = '2020-11-23'

>>> # Correctly quoted input is returned as the selected value
>>> cur.execute("""SELECT ? AS today""", (date,)) # <- execute requires a tuple as values
<sqlite3.Cursor object at 0x7f1fa205e1f0>
>>> cur.fetchone()
('2020-11-23',)

>>> # Unquoted input is evaluated as an expression!
>>> cur.execute(f"""SELECT {date} AS today""")
<sqlite3.Cursor object at 0x7f1fa205e1f0>
>>> cur.fetchone()
(1986,)
相关问题