tags:

views:

40

answers:

2

I am using python 2.7 and pymssql 1.9.908.

In .net to query the database I would do something like this:

using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection))
{
    com.Parameters.AddWithValue("@CustomerID", CustomerID);
    //Do something with the command
}

I am trying to figure out what the equivalent is for python and more particularly pymssql. I realize that I could just do string formatting, however that doesn't seem handle escaping properly like a parameter does (I could be wrong on that).

How do I do this in python?

A: 

Assuming PyMSSQL uses the Python DB API:

db = pymssql.connect('...')
for row in db.execute("SELECT * FROM Customer WHERE CustomerID = ?", [customer_id]):
    # do something with row
dan04
+1  A: 

After creating a connection object db:

cursor = db.execute('SELECT * FROM Customer WHERE CustomerID = %s', [customer_id])

then use any of the fetch... methods of the resulting cursor object.

Don't be fooled by the %s part: this is NOT string formatting, it's parameter substitution (different DB API modules use different syntax for parameter substitution -- pymssql just happens to use the unfortunate %s!-).

Alex Martelli
Thanks. The `%s` syntax was throwing me off.
Jason Webb
@Jason, you're welcome -- and the possible confusion is exactly why I call that syntax for DB API parameters "unfortunate" (though many popular DB API modules use it, alas).
Alex Martelli