【问题标题】:using correct syntax in pymysql for passing python variable to query在 pymysql 中使用正确的语法将 python 变量传递给查询
【发布时间】:2016-12-09 21:53:15
【问题描述】:

我正在尝试将作为字符串的变量 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")

【问题讨论】:

  • ,(x) 不应该是查询字符串的一部分。

标签: python mysql pymysql


【解决方案1】:

这行得通

sql="select verticalorg from tbl_employeedetails where empntid=(%s)"
args=x
a.execute(sql,args)

【讨论】:

    【解决方案2】:

    这应该适用于 python 3.4 及更高版本

    import pymysql
    #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()
    print(c)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 2019-11-03
      • 2020-11-24
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2016-03-17
      相关资源
      最近更新 更多