如何在Python中轻松地按格式连接列表中的字符串?

1 投票
1 回答
797 浏览
提问于 2025-04-18 01:58

我正在使用MySQLdb来往数据库中插入数据,当然我的代码大概是这样的:

db = MySQLdb.connect(host="111.111.111.111", port=3306,user="dba",passwd="somepass",db="somedb")
cursor = db.cursor()
cursor.execute("""
                    INSERT IGNORE INTO a (id,name) VALUES ('b', """+'diego' + """)""")

但是随着字段和数值的增加,这样写起来越来越麻烦。我得拼接字符串,还得仔细输入。

我该如何从两个列表中打印出execute的字符串参数,一个列表是字段,另一个列表是数值呢?

举个例子,我会有:

fields = ['id','name']
values = ['b','diego']

1 个回答

1
fields = ['id', 'name', 'row3', 'row4']
values = ['b', 'diego', 3, 4]

fields_str = (", ").join([x for x in fields])
values_str = (", ").join([("'" + str(x) + "'") for x in values])

cursor.execute("INSERT IGNORE INTO a (" + fields_str + ") VALUES (" + values_str + ")")

打印出连接在一起的字符串的值时,得到了这个结果:

INSERT IGNORE INTO a (id, name, row3, row4) VALUES ('b', 'diego', '3', '4')

撰写回答