Suppose I've connected to the server and I want to execute a couple of queries.
Lets say im connected to a database with a table called People.
People has the columns Age, Name, Height, and Weight.
conn = MySQLdb.connect(host = ......)
cursor1 = conn.cursor()
myName = 'Bob'
this. How do I use something that i've done in python inside my queries without getting errors?
cursor1.execute('''SELECT * FROM People WHERE Name = myName''')
I have also tried:
cursor1.execute('''SELECT * FROM People WHERE Name ='''+myName)
cursor1.execute("SELECT * FROM People WHERE Name = '"+str(myName) + "'")
cursor1.execute("'SELECT * FROM People WHERE Name ='" + str(myName) + "'")
cursor1.execute("'select * from People where Name ='" +"'"+str(myName)+"'")
I was advised to use escape quotes which I tried but my syntax was probably wrong
Any help would be appreciated. I feel very limited using mysqldb without being able to execute queries that use globally defined variables.
Thanks!!
You want to use %s to hold places for your arguments, and then pass a tuple of arguments as the second argument to execute:
cursor1.execute("SELECT * FROM People WHERE Name=%s", (myName,))
Thanks so much. Solved my problem.
cursor1.execute('SELECT * FROM People WHERE Name=%s', myName)
Log in to post a comment.
Suppose I've connected to the server and I want to execute a couple of
queries.
Lets say im connected to a database with a table called People.
People has the columns Age, Name, Height, and Weight.
conn = MySQLdb.connect(host = ......)
cursor1 = conn.cursor()
myName = 'Bob'
The query I want to execute is as follows. But I get an error when I run
this. How do I use something that i've done in python inside my queries
without getting errors?
cursor1.execute('''SELECT * FROM People WHERE Name = myName''')
I have also tried:
cursor1.execute('''SELECT * FROM People WHERE Name ='''+myName)
cursor1.execute("SELECT * FROM People WHERE Name = '"+str(myName) + "'")
cursor1.execute("'SELECT * FROM People WHERE Name ='" + str(myName) + "'")
cursor1.execute("'select * from People where Name ='" +"'"+str(myName)+"'")
I was advised to use escape quotes which I tried but my syntax was probably
wrong
Any help would be appreciated. I feel very limited using mysqldb without being
able to execute queries that use globally defined variables.
Thanks!!
You want to use %s to hold places for your arguments, and then pass a tuple of
arguments as the second argument to execute:
Thanks so much. Solved my problem.
cursor1.execute('SELECT * FROM People WHERE Name=%s', myName)