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

标签 python mysql python-2.7 pymysql

所以我从我的服务器获取了平均工资,并将其存储到一个python变量中,我想知道是否可以在后来的Python常见SQL中使用这个变量?我得到的平均值是“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()

和代码

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

不起作用,我不知道下一步该做什么

抱歉,我忘记包含错误:

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

添加三引号后,如下所示:

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

还是不行 错误:

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

最佳答案

所以我发现有两种方法可以在 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))

关于python - 如何在sql命令中使用python变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49905953/

相关文章:

python - Django - 如何使函数内部的变量可用于数据过滤器外部

mysql - 如何制作一个脚本来从 .xlsx (excel) 文件转储批量信息?

python - 如果我对每种情况都有返回,为什么我的 python 函数不返回任何值?

python - 如何使用 zeromq 和线程或异步处理对 python 程序的多个请求?

python - SQLAlchemy 从多对多关系中删除

python - 查找导致异常的执行路径

python - 为什么在Python中比较实例方法时 'is'不起作用

mysql - 获取数据库中表的最后更新时间

mysql - MSSQL 到 MYSQL - 从 MSSQL 中选择,插入 MySQL

Python - 排除两个日期之间的周末