Вопрос

I'm using MySQLdb for inserting to a database, naturally my code looks similar to this:

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' + """)""")

But it gets more and more cumbersome as more fields and values are added. I have to concatenate strings and sharp my eye to type in.

How can I print the execute string argument from two lists for fields and values, each?

For the example I would have:

fields = ['id','name']
values = ['b','diego']
Это было полезно?

Решение

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 + ")")

Printing the value of the concatenated string returned this for me:

INSERT IGNORE INTO a (id, name, row3, row4) VALUES ('b', 'diego', '3', '4')
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top