How to use python variable in sql command

时间:2018-04-18 17:46:21

标签: python mysql python-2.7 pymysql

So I have got the average salaries from my server, and store into a python variable and I want to know is that possible to use this variable in the later SQL common in python? and I got the avg is '51777'

connection = pymysql.connect (host = "...",
                          user = "...",
                          passwd = "...",
                          db = "...")
cursor = connection.cursor()





# select employeeID from employees table  using where, group by, and order by




cursor.execute("\
select title, avg(salaries) \
from employees group by title;")

x = cursor.fetchall()
print x


#store the value calculated from the table
cursor.execute("\
select avg(salaries) \
from employees;")

y = cursor.fetchall()
print y
z = y[0]
z = int(z[0])
print z

#using the variable into sql command
cursor.execute("select employeeID \
from employees where salaries > %s)", (z))

a = cursor.fetchall()
print a

cursor.close()
connection.close()

and the code

 #using the variable into sql command
    cursor.execute("select employeeID \
    from employees where salaries > %s)", (z))

doesn't work and I am not sure what to do next

Sorry I forgot to contain the error:

ProgrammingErrorTraceback (most recent call last)

W:\My Documents\calsses\2018 spring\MGMT 590\project\other queries.py in <module>()
     38 #using the variable into sql command
     39 cursor.execute("select employeeID \
---> 40 from employees where salaries > %s)", (z,))
     41 
     42 a = cursor.fetchall()
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\cursors.py in execute(self, query, args)
    164         query = self.mogrify(query, args)
    165 
--> 166         result = self._query(query)
    167         self._executed = query
    168         return result
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\cursors.py in _query(self, q)
    320         conn = self._get_db()
    321         self._last_executed = q
--> 322         conn.query(q)
    323         self._do_get_result()
    324         return self.rowcount
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in query(self, sql, unbuffered)
    833                 sql = sql.encode(self.encoding, 'surrogateescape')
    834         self._execute_command(COMMAND.COM_QUERY, sql)
--> 835         self._affected_rows = self._read_query_result(unbuffered=unbuffered)
    836         return self._affected_rows
    837 
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in _read_query_result(self, unbuffered)
   1017         else:
   1018             result = MySQLResult(self)
-> 1019             result.read()
   1020         self._result = result
   1021         if result.server_status is not None:
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in read(self)
   1300     def read(self):
   1301         try:
-> 1302             first_packet = self.connection._read_packet()
   1303 
   1304             if first_packet.is_ok_packet():
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in _read_packet(self, packet_type)
    979 
    980         packet = packet_type(buff, self.encoding)
--> 981         packet.check_error()
    982         return packet
    983 
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in check_error(self)
    391             errno = self.read_uint16()
    392             if DEBUG: print("errno =", errno)
--> 393             err.raise_mysql_exception(self._data)
    394 
    395     def dump(self):
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\err.py in raise_mysql_exception(data)
    105         errval = data[3:].decode('utf-8', 'replace')
    106     errorclass = error_map.get(errno, InternalError)
--> 107     raise errorclass(errno, errval)

ProgrammingError: (1064, u"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 ')' at line 1") 

After I add triple quotes like this:

cursor.execute('''select employeeID
from employees where salaries > %s)''', (z,))

and still doesn't work Error:

ProgrammingErrorTraceback (most recent call last)
W:\My Documents\calsses\2018 spring\MGMT 590\project\other queries.py in <module>()
     38 #using the variable into sql command
     39 cursor.execute('''select employeeID
---> 40 from employees where salaries > %s)''', (z,))
     41 
     42 a = cursor.fetchall()
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\cursors.py in execute(self, query, args)
    164         query = self.mogrify(query, args)
    165 
--> 166         result = self._query(query)
    167         self._executed = query
    168         return result
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\cursors.py in _query(self, q)
    320         conn = self._get_db()
    321         self._last_executed = q
--> 322         conn.query(q)
    323         self._do_get_result()
    324         return self.rowcount
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in query(self, sql, unbuffered)
    833                 sql = sql.encode(self.encoding, 'surrogateescape')
    834         self._execute_command(COMMAND.COM_QUERY, sql)
--> 835         self._affected_rows = self._read_query_result(unbuffered=unbuffered)
    836         return self._affected_rows
    837 
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in _read_query_result(self, unbuffered)
   1017         else:
   1018             result = MySQLResult(self)
-> 1019             result.read()
   1020         self._result = result
   1021         if result.server_status is not None:
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in read(self)
   1300     def read(self):
   1301         try:
-> 1302             first_packet = self.connection._read_packet()
   1303 
   1304             if first_packet.is_ok_packet():
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in _read_packet(self, packet_type)
    979 
    980         packet = packet_type(buff, self.encoding)
--> 981         packet.check_error()
    982         return packet
    983 
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\connections.py in check_error(self)
    391             errno = self.read_uint16()
    392             if DEBUG: print("errno =", errno)
--> 393             err.raise_mysql_exception(self._data)
    394 
    395     def dump(self):
C:\Program Files\Enthought\Canopy\edm\envs\User\lib\site-packages\pymysql\err.py in raise_mysql_exception(data)
    105         errval = data[3:].decode('utf-8', 'replace')
    106     errorclass = error_map.get(errno, InternalError)
--> 107     raise errorclass(errno, errval)

ProgrammingError: (1064, u"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 ')' at line 2") 

1 个答案:

答案 0 :(得分:0)

因此我有两种方法可以在python 2.7中解决这个问题,我认为最好分享这个解决方案。所以它失败的主要原因是我没有将变量转换为字符串,为了在python中使用SQL命令,我们必须转换SQL命令。所以有两种方法可以解决这个问题:

#1

cursor.execute('''select employeeID,FirstName, LastName
from employees where salaries > ''' + str(z) + ''';''')

#2

cursor.execute('''select employeeID,FirstName, LastName 
from employees 
where salaries > %s ;''' %(z))