Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MySQL in Flask

Can someone share example codes in Flask on how to access a MySQL DB? There have been documents showing how to connect to sqlite but not on MySQL.

Thank you very much in advance

like image 683
jaysonpryde Avatar asked Mar 23 '12 19:03

jaysonpryde


People also ask

Which database is best for Flask?

Flask can use SQLite and MySQL as a backend database. We recommend that you use SQLAlchemy as ORM with these relational databases.

Can't connect to MySQL server on localhost in Flask?

Most likely, it's the issue of mysql server which is either not running or you are providing unauthorized credentials while connecting to DB. Also, check the connection from command prompt. by typing command mysql on shell.

Can I use MySQL with Python?

Python needs a MySQL driver to access the MySQL database. In this tutorial we will use the driver "MySQL Connector". We recommend that you use PIP to install "MySQL Connector". PIP is most likely already installed in your Python environment.


2 Answers

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() 
like image 67
orange Avatar answered Sep 21 '22 02:09

orange


from flask import Flask from flask_sqlalchemy import SQLAlchemy  app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@server/db' db = SQLAlchemy(app)   class User(db.Model):     id = db.Column(db.Integer, primary_key=True)     username = db.Column(db.String(80), unique=True)     email = db.Column(db.String(120), unique=True)      def __init__(self, username, email):         self.username = username         self.email = email      def __repr__(self):         return '<User %r>' % self.username 

help link

like image 26
Sparkxxf Avatar answered Sep 21 '22 02:09

Sparkxxf