python - 在 python 中形成 MySQL 查询的正确方法是什么?

标签 python sql mysql

我是 python 的新手,我来自 PHP 的土地。我根据我的 PHP 知识在 python 中构建了一个这样的 SQL 查询,我收到了警告和错误

cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID = " + str(postid))
# rowcount here is int

形成查询的正确方法是什么?

此外,我如何转义字符串以形成 SQL 安全字符串?比如如果我想转义 -、'、"等,我曾经使用 addslashes。我们如何在 python 中做到这一点?

谢谢

最佳答案

首先,是时候学习使用 Matus 表达的方法安全地将变量传递给查询了。更清晰,

tuple = (foovar, barvar)
cursor.execute("QUERY WHERE foo = ? AND bar = ?", tuple)

如果你只需要传递一个变量,你仍然必须使它成为一个元组:在末尾插入逗号以告诉 Python 将其视为一个元组:tuple = (onevar,)

您的示例将采用以下形式:

cursor_.execute("update posts set comment_count = comment_count + ? where id = ?",
                (cursor_.rowcount, postid))

您还可以像这样使用命名参数:

cursor_.execute("update posts set comment_count = comment_count + :count where id = :id",
                {"count": cursor_.rowcount, "id": postid})

这次参数不是一个元组,而是一个由"key": value 成对组成的字典。

关于python - 在 python 中形成 MySQL 查询的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3948309/

相关文章:

python - 如何使用 psycopg2 在 PostgreSQL 中创建表?

python - 在 AppEngine 项目之外使用 Google AppEngine 数据存储

php - 正在使用 "require_once "影响网站速度

python - mariadb游标参数标记问题

python - 使用python将字符数组转换为整数

sql - 如何从sql数据库表列中删除特定字符?

mysql - 计算列中的不同值,如果在Where子句中没有找到则返回零

python - 无法同步数据库

java.lang.RuntimeException : Could not inject members 错误

python - Elasticsearch - field_value_factor,缺少参数