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

时间:2016-12-09 21:53:15

标签: 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")

2 个答案:

答案 0 :(得分:0)

这有效

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

答案 1 :(得分:0)

这应该适用于python 3.4及以上版本

FATAL EXCEPTION: main Process: firstdynamic.iberacha, PID: 8520 java.lang.UnsupportedOperationException: This is not supported, use MenuItemCompat.setOnActionExpandListener()
at android.support.v7.view.menu.MenuItemImpl.setOnActionExpandListener(MenuItemImpl.java:745)
at firstdynamic.iberacha.Food.onCreateOptionsMenu(Food.java:87)
at android.app.Activity.onCreatePanelMenu(Activity.java:3373)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:320)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:95)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:333)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:95)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)