错误:“ MySQL”对象没有属性“连接” /“ MySQL”对象没有属性“ get_db”

时间:2018-12-11 10:26:20

标签: python flask mysql-workbench

我是不熟悉烧瓶的人,正在编写一个用于登录的基本程序。每次我修改时,我都会遇到上述错误。下面是我的代码供参考。有人可以纠正我吗?

@app.route('/')
def index():
    return render_template('form_ex.html')

@app.route('/',methods = ['POST'])
def Authenticate():

    login = request.form['u']
    password = request.form['p']
    cursor = mysql.get_db().cursor()
    cursor.execute("SELECT * FROM UserLogin WHERE login=%s and password=%s")
    data= cursor.fetchone()

    if data is None:

        return("Username or password incorrect")
    else:
        return("You are logged in")

1 个答案:

答案 0 :(得分:1)

根据您未初始化MySQL DB的代码的外观,从此链接获取的答案如下:Using MySQL in Flask

首先,您需要安装Flask-MySQL软件包。以pip为例:

pip install flask-mysql

接下来,您需要添加一些配置并初始化MySQL:

from flask import Flask
from flaskext.mysql import MySQL

app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
Now you can get connection and cursor objects and execute raw queries:

conn = mysql.connect()
cursor =conn.cursor()

cursor.execute("SELECT * from User")
data = cursor.fetchone()