gpt4 book ai didi

python - 将包含多个项目的列表插入 mysql 数据库

转载 作者:行者123 更新时间:2023-11-30 01:35:25 25 4
gpt4 key购买 nike

我有一个这样的列表:

list = [('name1', 'id1', 'created_at1'),('name2', 'id2', 'created_at2'),('name3', 'id3', 'created_at3')]

我想使用 MySQLdb 将它放入 Mysql 数据库中,最终看起来像这样:

Name   ID    Created_at
name1 id1 created_at1
name2 id2 created_at2
name3 id3 created_at3

我尝试过类似的方法:

for s in list:
var_string = ', '.join('?' * len(s))
query_string = 'INSERT INTO TweetsTest VALUES (%s);' % s
cursor.execute(query_string, varlist)

但是它不起作用。我怎样才能实现这个目标?

最佳答案

这应该可以做到:

sql = ("INSERT INTO TweetsTest "
"(Name, ID, Created_at) VALUES ")

for item in list:
sqlRow = "('%s', '{1}', '{2}'), ".format(item[1], item[2]) % item[0]
sql += sqlRow

sql = sql[:-2] + ";"
cursors.execute(sql)

以上所有内容都意味着这 3 个字段都是基于字符串的,因此 for 循环中的引号。对于所有数字字段 - 删除引号。

关于python - 将包含多个项目的列表插入 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16961058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com