简体   繁体   中英

Mysql query using python

I'm using python 3.x and mysql.connector to access a Mysql database. I'm having an issuing with querying the database.

When I run the following query, I get the correct result:

cursor.execute("SELECT idx FROM db WHERE name = 'John Smith'")

When I try and run the following query I get an error:

cursor.execute("SELECT idx FROM db WHERE name = %s",'John Smith')

File "<input>", line 1, in <module>
  File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 515, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.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 '%s' at line 1

I've tried running the following query instead, but it appears that the query searches for "%s" not the string "John Smith"

cursor.execute("SELECT idx FROM db WHERE name = '%s'",'John Smith')

I'm not sure if the error is due to the fact that I'm using a string with spaces in it or not, but I haven't been able to solve the problem.

q="SELECT idx FROM db WHERE name = %s";

cursor.execute(q,'Xander')

According to the docs, you would need to write:

 cursor.execute("SELECT idx FROM db WHERE name = %s", ('John Smith'))

In other words, the parameter-replacement values must be contained in an iterable.

(But see the answer from theClap who correctly adds a semi-colon to force "tupleness" where required).

Formatting just needs to be changed a little. You were pretty close.

foo = 'John Smith'
cursor.execute("SELECT idx FROM db WHERE name = %s", (foo,))

Take a gander at the links below for more explanation
Python MySQL Parameterized Queries
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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