【问题标题】:How to use python variable in sql command如何在sql命令中使用python变量
【发布时间】:2018-09-29 01:32:48
【问题描述】:

所以我从我的服务器获得了平均工资,并存储到一个 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") 

【问题讨论】:

  • ...where salaries &gt; %s)", (z,))。您没有包含错误,但我猜问题是z 之后缺少逗号。
  • 您是否收到错误消息?如果是,请添加完整的 Traceback 错误。
  • 另外,在查询中使用三引号,而不是 `\`,可以让您创建更清晰的查询。
  • 好的,所以问题是 2 倍的。将字符串括在三引号中,删除 \ 字符,并将 z 作为元组提供。
  • 我试过你提供的方法还是不行

标签: python mysql python-2.7 pymysql


【解决方案1】:

所以我找到了两种在 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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 2016-05-02
    • 2019-03-21
    • 1970-01-01
    • 2022-01-08
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多