Forming database connection between Maria db and Python-Flask

Dul’s Blog
Oct 16, 2020

--

How to connect Maria db and Python Flask

Maria db and Python Flask

Hi, let’s start off by importing Maria db into your app.py of Python-Flask.

import mariadb

Now add the url of host, the port, user, the Maria db database credentials to establish connection between python-flask and Maria db.

conn = mariadb.connect(
host='127.0.0.1',
port= 3306,
user='root',
password='goldSTAR',
database='movieDb')

Now note that 127.0.0.1 means the same as localhost. Normally the default port of the database is 3306. The user of database is as you defined. Further the defined database in Maria db must be an already existing database. Now that we connected with the database we want to further perform SELECT,DELETE,INSERT or UPDATE queries on the database via our front end Python-Flask app. Hence let’s establish the cursor point.

cur = conn.cursor()

The complete code in Python-Flask app.py.

from flask import Flask
import mariadb
app = Flask(__name__)conn = mariadb.connect(
host='127.0.0.1',
port= 3306,
user='root',
password='goldSTAR',
database='movieDb')
cur = conn.cursor()
@app.route("/index")
def index():
return "Connected to database"
if __name__ == "__main__":
app.run()

You can read my blog Database querying and Python-Flask to learn how to query SELECT,DELETE,INSERT and UPDATE the databases. Also to find the credentials to connect with a database read the blog. Thanks for reading. Have fun coding…..

--

--