我正在努力将此 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+'%'))
关于python - 通过 Python 命令运行 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43382495/