python - 在 pymysql 中使用正确的语法将 python 变量传递给查询

标签 python mysql pymysql

我试图将变量 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/

相关文章:

Python 生成随机 : uuid v. md5 v. random 哪个最有效或*低效*

python - 如何使用 range 函数将空格插入字符串?

python - 使用 tkMessageBox 时摆脱顶层 tk panedwindow

mysql - 更清晰的 SQL 查询

python - django 1.5 + pymysql 错误 : ImportError: cannot import name Thing2Literal

python - 预生成用于 python 的 GUID?

php - 计算特定行/偏移量的分页偏移量

php - 检索 twitter 之类的用户名链接 php

用户 root@localhost 的 mysql 访问被拒绝(使用密码 : NO) despite having set a password and entered it in connection uri

python - PyMySQL 使用 localhost 与套接字不一致行为