就像在mysql connector / python中一样

时间:2014-06-05 23:55:00

标签: python mysql mysql-python

我第一次使用mysql-connector / python而且我遇到了错误。 我想从名为net的mysql表中获取blah的电子邮件地址。

cursor = cnx.cursor()
p = "net"
query = ("SELECT * FROM blah WHERE email LIKE %s limit 10", ("%" + p + "%",))
cursor.execute(query,(p,))
for row in cursor:
    print row
cursor.close()
cnx.close() 

我收到此错误

Traceback (most recent call last):
  File "<input>", line 9, in <module>
  File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 491, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 683, in cmd_query
    statement))
  File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 601, in _handle_result
    raise errors.get_exception(packet)
ProgrammingError: 1064 (42000): 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 '"SELECT * FROM blah WHERE email LIKE %s limit 10", ("%" + p +"%")' at line 1

任何人都可以建议为什么代码不起作用?它正在使用sql -

select * from blah where email LIKE "%net" limit 10

2 个答案:

答案 0 :(得分:3)

试试这个:

query = "SELECT * FROM blah WHERE email LIKE CONCAT('%', %s, '%') limit 10"
cursor.execute(query,(p,))

您需要在字符串中保留%s,以便MySQL Connector可以替换execute参数。您将query设置为列表,而不是字符串。

答案 1 :(得分:2)

cursor.execute的第一个参数应该是一个字符串,看起来你已经分配了字符串并调用了函数。可能应该看起来像:

query = "SELECT * FROM blah WHERE email LIKE %s limit 10"
cursor.execute(query,("%" + p + "%",))