Reputation: 753
I have a list of tuples that I'm trying to 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') "
Upvotes: 2
Views: 2947
Reputation: 753
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)
Upvotes: 2
Reputation: 11545
>>> 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.
Upvotes: 1
Reputation: 319621
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.
Upvotes: 1
Reputation: 5949
This:
",".join( x+","+y for x,y in lst )
will produce:
'val,val,val,val,val,val'
Upvotes: 1
Reputation: 123841
Like this?
>>> l=[('val', 'val'), ('val', 'val'), ('val', 'val')]
>>> ','.join(map(','.join,l))
'val,val,val,val,val,val'
Upvotes: 4