Boole
Boole

Reputation: 3

Passing variable into MySQL using Python 2.7

I've been trying to insert a string value from a variable in Python 2.7 into a MySQL statement. I can't seem to get it to work, could someone point me in the right direction?

import MySQLdb

country_name = raw_input("Which country would you like?\n")

dbh = MySQLdb.connect(host="localhost",
                      user="boole",
                      passwd="****",
                      db="mySQL_Experiment_1")
sth = dbh.cursor()
sth.execute("""SELECT name, population FROM world WHERE name=(%s)""", (country_name))
for row in sth:
    print row[0], row[1]

It outputs:

/usr/bin/python2.7 "/home/boole/Documents/Python Scripts/mySQL_Experiment_1/main.py"
Which country would you like?
Canada
Traceback (most recent call last):
  File "/home/boole/Documents/Python Scripts/mySQL_Experiment_1/main.py", line 10, in <module>
    sth.execute("""SELECT name, population FROM world WHERE name=(%s)""", (country_name))
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
    query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

Process finished with exit code 1

Thanks, Boole

Upvotes: 0

Views: 346

Answers (1)

Prateek
Prateek

Reputation: 1556

Try this

cursor.execute("SELECT name, population FROM world where name = %s", [country_name])

Upvotes: 1

Related Questions