Divya Pai
Divya Pai

Reputation: 1

error: 'MySQL' object has no attribute 'connection'/ 'MySQL' object has no attribute 'get_db'

I am new to flask and i am writing a basic program for login. Everytime I ammend i end with error mentioned above. below is my code for reference. Can someone please correct me.

@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")

Upvotes: 0

Views: 1369

Answers (1)

user10775237
user10775237

Reputation:

By the looks of the code you didn't initialise the MySQL DB, taken from this link the answer is below: Using MySQL in Flask

Firstly you need to install Flask-MySQL package. Using pip for example:

pip install flask-mysql

Next you need to add some configuration and initialize 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()

Upvotes: 1

Related Questions