python mysql where 子句中的错误

error in python mysql where clause

我是 python 的新手。编写了一个小代码来连接到数据库并从数据库中获取数据。我正在使用 python 3.4 和 mysql.connector 连接数据库

HTML 表单用于获取用户名和密码。代码如下

<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代码是从html中获取值,然后赋值给name和password。 sql 语句用于通过使用 WHERE 子句

从数据库中获取密码

python代码

#!"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)

但是where子句的赋值错误。我没有得到什么语法错误。请给出建议 错误为:

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>

你错过了单引号,正如@Matthias 所说,第二个参数是一个元组。

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