如何在python中使用SQL参数?

Jas*_*ebb 13 python pymssql

我使用的是python 2.7和pymssql 1.9.908.

在.net中查询数据库我会做这样的事情:

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

我试图弄清楚python的等价物是什么,尤其是pymssql.我意识到我可以只进行字符串格式化,但是这似乎没有像参数一样正确地进行转义(我可能错了).

我怎么在python中这样做?

Ale*_*lli 20

创建连接对象后db:

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

然后使用fetch...结果cursor对象的任何方法.

不要被这%s部分所欺骗:这不是字符串格式化,它是参数替换(不同的DB API模块使用不同的语法进行参数替换 - pymssql碰巧使用了不幸的%s! - ).

  • 请注意,python3上最新的pymssql不喜欢`[customer_id]`,它想要一个元组`(customer_id,)` (6认同)
  • 谢谢.`%s`语法让我失望. (2认同)