error in python mysql where clause

3.4k views Asked by At

I am newbie to python .written a small code to connect to database and fetch the data from database .I am using python 3.4 and mysql.connector to connect the database

HTML form is used to get the name and password .code is as given below

<html>  
<head>  
<title>test</title>  
<link rel="stylesheet" type="text/css" href="wel.css">
</head>  
<body>  
<form action="/cgi-bin/python1.py" method="post">
<label>First Name: <input type="text" name="first_name"></label><br />

<label>Password:<input type=password name="pass" /></label><br />

<input type="submit" value="Submit" />
</form> 
</body>  
</html> 

python code is to get value from html from then assigned to name and password. sql statement is used to fetch the password from the database by using WHERE clause

python code

#!"C:\python34\python.exe"
import cgitb ,cgi
import sys
import mysql.connector
cgitb.enable()
form = cgi.FieldStorage() 
print("Content-Type: text/html;charset=utf-8")
print()

# Get data from fields
first_name = form.getvalue('first_name')
password = form.getvalue('pass')
print (password)
conn = mysql.connector.connect(host='localhost',port='8051',
                                       database='example',
                                       user='root',
                                       password='test')                                
cursor = conn.cursor()                                 
if conn.is_connected():
    print('Connected to MySQL database')
cursor.execute("""SELECT pass FROM tablename1 where  name = %s""",(first_name))
for row in cursor.fetchall():
        print (row)

But the error in assign of where clause .I am not getting what syntax error .please give suggestions error as :

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 
      args = (1064, "1064 (42000): You have an error in your SQL synt...n for the right syntax to use near '%s' at line 1", '42000') 
      errno = 1064 
      msg = "You have an error in your SQL syntax; check the ...n for the right syntax to use near '%s' at line 1" 
      sqlstate = '42000' 
      with_traceback = <built-in method with_traceback of ProgrammingError object>
1

There are 1 answers

3
liushuaikobe On BEST ANSWER

You missed the single quotes, and as @Matthias said, the second param is a tuple.

cursor.execute("""SELECT pass FROM tablename1 where name='%s'""", (first_name, ))