python - python mysql where子句中的错误

标签 python html mysql apache localhost

我是 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, ))

关于python - python mysql where子句中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702619/

相关文章:

python - Scrapy - 遇到重复项时停止爬虫

Python:多线程下载器相互阻塞

python - 要求用户提供输入,直到他们给出有效的答复

html - 我如何在 Joomla 模块中的 </body> 标签附近添加 HTML?

javascript - 使用 javascript 访问 php 变量

python - 为列表的最后一项运行不同的函数

html - display flex 不会像预期的那样打断长行

javascript - Coldfusion - 验证是否选中单选按钮

mysql - 无法在 cPanel 中创建此存储过程

MySQL 'Truncated incorrect INTEGER value'