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

7bsow1i6  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(428)

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

wlwcrazw1#

因此,我在Python2.7中找到了两种方法来解决这个问题,我认为最好是分享这个方法的解决方案。所以它失败的主要原因是我没有将变量转换成字符串,为了在python中使用sql命令,我们必须在python中转换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))

相关问题