views:

174

answers:

5

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

Like this?

>>> l=[('val', 'val'), ('val', 'val'), ('val', 'val')]
>>> ','.join(map(','.join,l))
'val,val,val,val,val,val'
S.Mark
Kind of. My goal is to preserve the parenthesis. I changed the OP.
matt
matt, You could try `','.join(map(str,l))` to get `"('val', 'val'),('val', 'val'),('val', 'val')"`, but I still think you need to use MySQLdb functions instead of making up string.
S.Mark
+1  A: 

This:

",".join( x+","+y for x,y in lst )

will produce:

'val,val,val,val,val,val'
Charles Beattie
+1  A: 

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.

SilentGhost
I changed the post again to show what I was thinking. Is it still a fauxpas?
matt
@matt: yes. What library are you using? What database? Do you have docs for it?
SilentGhost
MySQLdb, I guess I'll start the Googlin. I don't understand why it's a bad practice. I could pull in everything off a csv and put it in the table easily. (Assuming I actually could)
matt
@matt: [Official docs for MySQLdb](http://mysql-python.sourceforge.net/MySQLdb.html#some-examples) show how to do exactly what you want
SilentGhost
+1  A: 
>>> 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.

Santa
Since nobody has yet explained explicitly, I assume the reason it's unsafe is that if L contains user-supplied values, a malicious user could supply a value that would execute arbitrary SQL commands on your database.
nekomatic
+1  A: 

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)
matt
Since your answer is the most direct and appropriate for your true issue (and for your question, after the edit), you should select it as “the” answer by clicking on the check mark below its number of votes.
ΤΖΩΤΖΙΟΥ