Automagically expanding a Python list with formatted output

Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.

For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "IN" clause.

import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]

mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()

sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"

mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()

Any help would be appreciated!

Answers


try:

",".join( map(str, record_ids) )

",".join( list_of_strings ) joins a list of string by separating them with commas

if you have a list of numbers, map( str, list ) will convert it to a list of strings


Need Your Help

Prolog DCG illustration please

prolog grammar dcg

Currently I am playing with DCG in Prolog to parse an XML file. I was able to get the following code snippet which is able to parse a simple XML such as:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.