我试图将变量 x 传递给 python 查询以获取输出,它是一个字符串。我正在使用 pymysql 。但是,当我运行它时出现错误:
注意:我暂时注释掉了x的导入,它实际上是用户在登录页面输入的用户名
import pymysql
import pymysql.cursors
#from Roster import x
x='bh16'
IT = pymysql.connect(host='xx.xxx.xx.xx', user='xxxx', password='xxxx',
db='xxxx')#Connect to the IT database
Others = pymysql.connect(host='xx.xx.xx.x0', user='xxxxxxx', password='xxxx',
db='samsdb')#Connect to the non IT database
a=IT.cursor() # Open Cursor for IT database
b=Others.cursor()#Open Cursor for non-IT database
m='''(select verticalorg from tbl_employeedetails where empntid=%s,(x))'''
a.execute(m)
b.execute(m)
c=a.fetchall()
d=b.fetchall()
q=c+d
print(q)
错误:
File "C:\Python35\lib\site-packages\pymysql-0.7.9-py3.5.egg\pymysql\connections.py", line 981, in _read_packet
packet.check_error()
File "C:\Python35\lib\site-packages\pymysql-0.7.9-py3.5.egg\pymysql\connections.py", line 393, in check_error
err.raise_mysql_exception(self._data)
File "C:\Python35\lib\site-packages\pymysql-0.7.9-py3.5.egg\pymysql\err.py", line 107, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s,(x))' at line 1")
最佳答案
这有效
sql="select verticalorg from tbl_employeedetails where empntid=(%s)"
args=x
a.execute(sql,args)
关于python - 在 pymysql 中使用正确的语法将 python 变量传递给查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41069487/