Matthew Tuman
Matthew Tuman

Reputation: 49

passing a python variable into a mysql select statement

Hi I have the following block of code that is meant to take the variable 'search_value'and pass it into the WHERE clause of a mysql select statement

 import MySQLdb

 search_term = input('Enter your search term: ')

 print (search_term)

 conn = MySQLdb.connect(my connection info)

 c = conn.cursor()

 q = "SELECT * FROM courses WHERE course_area = %(value)s "

 params = {'value': search_term}

 c.execute(q, params)

 rows = c.fetchall()

 for eachRow in rows:
     print (eachRow)

I know that I need to use %s somewhere but I'm not sure of the exact syntax. I did some searching online but I have only found examples of insert statement...and I know they have a little different syntax. Thanks

Upvotes: 0

Views: 2914

Answers (1)

gold_cy
gold_cy

Reputation: 14216

This should work:

q = "SELECT * FROM courses WHERE course_area = %(value)s "
params = {'value':'some_value_here'}
c.execute(q, params)
.....

Upvotes: 0

Related Questions