如何在python中使用SQL参数?
我正在使用python 2.7和 在.net中,要查询数据库,我将执行以下操作:如何在python中使用SQL参数?,python,pymssql,Python,Pymssql,我正在使用python 2.7和 在.net中,要查询数据库,我将执行以下操作: using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection)) { com.Parameters.AddWithValue("@CustomerID", CustomerID); //Do something with the command }
using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection))
{
com.Parameters.AddWithValue("@CustomerID", CustomerID);
//Do something with the command
}
我试图找出python的等价物,尤其是pymssql。我意识到我可以只做字符串格式化,但这似乎不像参数那样正确地处理转义(我可能在这方面错了)
在python中如何执行此操作?在创建连接对象后
db
:
cursor = db.execute('SELECT * FROM Customer WHERE CustomerID = %s', [customer_id])
然后使用所生成的游标
对象的任何fetch…
方法
不要被
%s
部分愚弄:这不是字符串格式,而是参数替换(不同的DB API模块使用不同的语法进行参数替换——pymssql恰好使用了不幸的%s
!-)。谢谢。%s
语法让我很反感。@Jason,不客气——而可能的混淆正是为什么我将DB API参数的语法称为“不幸”(尽管许多流行的DB API模块都使用它,唉)。该死的,这种误导性的%s语法!我刚刚花了一个小时试图理解为什么我的代码抱怨试图使用%d指定int参数。我被引导认为这里使用的是Python格式。请注意,python3上最新的pymssql不喜欢[customer\u id]
,它需要一个元组(customer\u id,)
非常好的问题和答案。有没有人知道如何像Jason那样使用命名参数。到目前为止,我只能使用%s,%d种类型的内容(位置)。