如何在 python 中的 SQL 查询上动态绑定多个参数?

How to dynamically bind multiple parameters on SQL query in python?

所以,我有一个 table(比如 table_name),它的列是:

|  A   |  B   |  C   |
------------------------
|  a1  |  b1  |  c1  |
|  a2  |  b2  |  c2  |
   ...

现在我必须使用以下查询读取列数据:

import pandas as pd
import pymysql as pycon

con = pycon.connect(host='localhost',user='root',password='', db='database')

#Error in here
df= pd.read_sql_query("SELECT A from table_name where B = %s and C != %s" %variableB %variableC, con)

但是我在read_sql_query(...)中遇到了一个错误,可能是查询格式错误,因为动态绑定的单个参数可以正常工作 即

df= pd.read_sql_query("SELECT A from table_name where B = %s" %variableB, con)

工作 w/o 错误。谁能帮我查询一下?

当你将多变量绑定到字符串时,语法应该是这样的

df= pd.read_sql_query("SELECT A from table_name where B = %s and C != %s" % (variableB, variableC), con)

如果有人 运行 遇到同样的问题,正确的查询代码是 '%s' 而不是 %s

df= pd.read_sql_query("SELECT A from table_name where B = '%s' and C != '%s'" % (variableB, variableC), con)

下面的代码给了我 pymysql.err.InternalError.

df= pd.read_sql_query("SELECT A from table_name where B = %s and C != %s" % (variableB, variableC), con)

谢谢 Whosebug :)