简体   繁体   English

如何在python中使用SQL参数?

[英]How do I use SQL parameters with python?

I am using python 2.7 and pymssql 1.9.908 . 我使用的是python 2.7和pymssql 1.9.908

In .net to query the database I would do something like this: 在.net中查询数据库我会做这样的事情:

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. 我试图弄清楚python的等价物是什么,尤其是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? 我怎么在python中这样做?

After creating a connection object db : 创建连接对象db

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

then use any of the fetch... methods of the resulting cursor object. 然后使用生成的cursor对象的任何fetch...方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM