0

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

6
  • What happens when you run this? Commented Aug 8, 2016 at 11:26
  • Sorry, I knew I forgot something! Commented Aug 8, 2016 at 11:28
  • Try this cursor.execute("SELECT name, population FROM world where name = %s", [country_name]) Commented Aug 8, 2016 at 11:35
  • Thanks @Prateek it worked perfectly! Commented Aug 8, 2016 at 12:36
  • @Boole You are welcome, I will write it down as an answer please do mark it as a correct solution to your problem. So that it becomes useful for others if they are facing this issue. Commented Aug 9, 2016 at 5:10

1 Answer 1

1

Try this

cursor.execute("SELECT name, population FROM world where name = %s", [country_name])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.