How to turn a list of tuples into a string?
I have a list of tuples that I'm trying t开发者_StackOverflow中文版o incorporate into a SQL query but I can't figure out how to join them together without adding slashes. My like this:
list = [('val', 'val'), ('val', 'val'), ('val', 'val')]
If I turn each tuple into a string and try to join them with a a comma I'll get something like
' (\'val\, \'val\'), ... '
What's the right way to do this, so I can get the list (without brackets) as a string?
I want to end up with::
q = """INSERT INTO test (feed,site) VALUES %s;""" % string
string = " ('val', 'val'), ('val', 'val'), ('val', 'val') "
Like this?
>>> l=[('val', 'val'), ('val', 'val'), ('val', 'val')]
>>> ','.join(map(','.join,l))
'val,val,val,val,val,val'
Using MySQLdb, executemany does this.
cursor = db.cursor()
vals = [(1,2,3), (4,5,6), (7,8,9), (2,5,6)]
q = """INSERT INTO first (comments, feed, keyword) VALUES (%s, %s, %s)"""
cursor.executemany(q, vals)
This:
",".join( x+","+y for x,y in lst )
will produce:
'val,val,val,val,val,val'
You shouldn't be doing this. Have a look at definition of the functions that are used to execute your SQL statement. They'll take care of formatting. SQL statement itself should only contain placeholders.
For example, official docs for MySQLdb show how to do exactly what you want.
>>> L = [('val', 'val'), ('val', 'val'), ('val', 'val')]
>>> ','.join([repr(tup) for tup in L])
"('val', 'val'),('val', 'val'),('val', 'val')"
Though, as others have pointed out, doing this in a string placeholder meant to be sent to MySQL is rather unsafe.
精彩评论