如何在Python中使用SQL参数?

14 投票
1 回答
28178 浏览
提问于 2025-04-16 02:20

我正在使用 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
}

我想弄清楚在 Python,特别是 pymssql 中,怎么做才能达到同样的效果。我知道我可以使用字符串格式化,但这样似乎没有像参数那样处理转义字符(我可能错了)。

在 Python 中我该怎么做呢?

1 个回答

25

在创建了一个连接对象 db 之后,运行 db.execute(query, params)

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

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

不要被 %s 这个部分误导:这不是字符串格式化,而是参数替换(不同的数据库API模块使用不同的语法来进行参数替换 -- pymssql恰好使用了这个不太好的 %s!)。

撰写回答