14

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?

Jason Webb
  • 7,938
  • 9
  • 40
  • 49
  • 1
    Excellent question and answers. Does anyone know how to use *NAMED* parameters like Jason has above. So far I've only be able to use %s, %d type of stuff (positional). – Michael Kennedy Dec 05 '13 at 18:49

1 Answers1

24

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
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 3
    Thanks. The `%s` syntax was throwing me off. – Jason Webb Aug 05 '10 at 14:17
  • @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 Aug 05 '10 at 14:29
  • 1
    Damn this misleading %s syntax! I just spent an hour trying to understand why my code complained for attempt to use %d for specifying an int parameter. I was led to think that it's the Python formatting that's in use here. – Passiday Oct 05 '13 at 08:58
  • 8
    Note that the latest pymssql on python3 doesn't like `[customer_id]`, it wants a tuple `(customer_id,)` – Perkins Mar 30 '16 at 18:36