如何在 python 中使用 SQL 参数? [英] How do I use SQL parameters with python?

查看:41
本文介绍了如何在 python 中使用 SQL 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 python 2.7 和 pymssql 1.9.908.

I am using python 2.7 and pymssql 1.9.908.

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

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
}

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

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

我如何在 python 中执行此操作?

How do I do this in python?

推荐答案

创建连接对象后db:

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

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

then use any of the fetch... methods of the resulting cursor object.

不要被 %s 部分所迷惑:这不是字符串格式化,而是参数替换(不同的 DB API 模块使用不同的语法进行参数替换——pymssql 恰好使用了不幸的%s!-).

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

这篇关于如何在 python 中使用 SQL 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆