How do I use SQL parameters with python?

纵然是瞬间 提交于 2019-11-26 04:02:12

问题


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?


回答1:


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!-).



来源:https://stackoverflow.com/questions/3410455/how-do-i-use-sql-parameters-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!