简体   繁体   English

如何在sql命令中使用python变量

[英]How to use python variable in sql command

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? 因此,我从服务器获取了平均薪水,并将其存储到python变量中,我想知道是否可以在以后的python通用SQL中使用此变量? and I got the avg is '51777' 我得到的平均值是“ 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) ProgrammingErrorTraceback(最近一次通话)

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") 

So there are two ways I find out to solve this in python 2.7 and I think it is better to share the solution for this one. 因此,我发现有两种方法可以在python 2.7中解决此问题,我认为最好共享此解决方案。 So the main reason why it fails is that I have not converted the variable into the string, in order to use the SQL command in python, we have to convert SQL command in. So there are two ways to solve this: 因此失败的主要原因是我没有将变量转换为字符串,为了在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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM