使用元组的 Python 列表将多行插入到数据库中 [英] Insert multiple rows into DB with Python list of Tuples

查看:73
本文介绍了使用元组的 Python 列表将多行插入到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组列表:

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

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

I want to update a table with multiple rows/values for a given ID (in this case ID = 1)

所以:

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

我在格式方面遇到了问题 - 我已将字符串简化为如下所示:

I'm having trouble with the format - I've gotten the string down to something like this:

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

但这当然行不通,因为元组周围有额外的括号.任何构建一种方法来pythonically"的想法?

But of course this doesn't work due to the extra parenthesis wrapped around the tuples. Any ideas for constructing a way to do this "pythonically?

推荐答案

好吧,你需要构造一行:

Well, you need to construct the line:

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)

这篇关于使用元组的 Python 列表将多行插入到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆