python - 通过 Python 命令运行 SQL

标签 python mysql

我正在努力将此 SQL 查询写入 Python 脚本。

所有变量都存储在Python中。我需要 SQL 语句来传递 python 变量,然后执行查询。

SQL 语句应在数据库中查询 col1、col2、col3 中的“this_string”,然后用 string1、string2 和 string3 更新 field1、field2 和 field3。

但是我想不通..

mystring = 'this_string'
string1 = 'test1'
string2 = 'test2'
string3 = 'test3'

UPDATE databaseb.name SET field1 = string1, field2 = string2, field3 = string3 WHERE CONCAT_WS('', column1,column2,column3) LIKE '%this_string%'

我试过了

conn = MySQLdb.connect(host= "1.2.3.4",
user="me",
passwd="passwd",
db="dbname",
use_unicode=True,
charset="utf8")
x = conn.cursor()
x.execute(UPDATE databaseb.name SET field1 = string1, field2 = string2, field3 = string3 WHERE CONCAT_WS('', column1,column2,column3) LIKE '%this_string%'
)
conn.commit()
conn.close()

最佳答案

查询应该用引号括起来,参数化 SQL 是一个很好的做法。它可能看起来像这样:

x.execute("""UPDATE databaseb.name SET field1 = %s, field2 = %s, field3 = %s WHERE CONCAT_WS('', column1,column2,column3) LIKE %s""",(string1, string2, string3, '%'+this_string+'%'))

引用:http://mysql-python.sourceforge.net/MySQLdb.html

关于python - 通过 Python 命令运行 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43382495/

相关文章:

python - 使用具有各种功能的字典过滤 pandas 数据框

python - Django 中的 i18n 和 l10n 具有不同的 View

python - 并行和条件 : NoneType object has no attribute '__dict__'

mysql - sql 检索 magento 中的所有订单和产品详细信息

mysql - 将字段编号替换为其在表 sql、mysql 中的行位置

python - 动态添加路线到 Pyramid

python - 在Python中使用数组以更方便的方式编写长switch语句

c# - Dapper 输出参数被 mysql 解释为 null

mysql - 在 hibernate 状态下提交事务

mysql - 在更新 Multi-Tenancy 数据库中的嵌套集时是否有替代方法来锁定表?