Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySQL Connector database query with %s fails

I have a basic program that is supposed to query a database that contains user information. I am trying to select the information for a specific user and print it out to the console.

Here is my code:

import mysql.connector

funcon = mysql.connector.connect(user='root', password='pass', host='127.0.0.1', database='fundata')
funcursor = funcon.cursor()

query = ("SELECT * FROM funtable WHERE userName=%s")
uName = 'user1'

funcursor.execute(query, uName)

for (userName) in funcursor:
    print("{}".format(userName))

I have the username stored in a variable because later I plan on getting the user name from a tkinter entry box. When I execute this code I get the following error:

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 have tried putting the %s in quotes in the query but then it literally searches for a user names '%s' and returns nothing. How can I change my code so I can query the database for only this user?

Thank you.

FYI: I am using python 3.3.

like image 521
Sebastian Bartholomew Charles Avatar asked May 12 '14 02:05

Sebastian Bartholomew Charles


People also ask

What is %s and %D in MySQL?

12 years, 10 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.

How are errors returned when a query or connection fails in MySQLdb?

InterfaceError: When database connection fails for some reason, MySQLdb will raise an InterfaceError. Note InterfaceError only get raise when there is internal problem in connection to the database, MySQLdb will not raise InterfaceError because of wrong database name or password.


1 Answers

Change your funcursor.execute(query, uName) call to:

funcursor.execute(query, (uName, ))

The second argument in execute takes a list/tuple of strings, not a string. The above call creates the tuple before passing in the string to execute, so no error is thrown.

The reason why execute takes a list/tuple of strings is because it does not know beforehand how many strings it needs in order to satisfy your query.

like image 183
huu Avatar answered Sep 20 '22 07:09

huu