1

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']
2
  • Should that name have apostrophes around it or am I misinterpreting what you meant? Commented Apr 9, 2014 at 4:58
  • I add the apostrophes as it's required for SQL sintax Commented Apr 9, 2014 at 4:59

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

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

INSERT IGNORE INTO a (id, name, row3, row4) VALUES ('b', 'diego', '3', '4')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.