-1

I want to Deploy my Flask app but the problem I am facing is with databases. I am using MySQL database. I want to use an online MySQL database for which I am using website www.freemysqlhosting.net I Have created the tables, But Now I am not getting how to use that servers credentials in my Flask app.

Kindly please Help...

2 Answers2

0

You need mysql database connector for python

import MySQLdb

db = MySQLdb.connect(
   host="hostname",     # your host 
   user="username",     # your username
   passwd="password",   # your password
   db="testdb")         # database name

you can flask-sqlalchemy package:

SQLALCHEMY_DATABASE_URI = 'mysql+mysqldb://username:password@host/database_name' 
metmirr
  • 4,234
  • 2
  • 21
  • 34
0

Before the code you need install * MySQL connector for Python Flask and mysqldb

Use : pip install flask Use : pip install flask_mysqldb Use : pip install pip install flask-mysql Use : pip install MySQL-python Use : pip install mysql-connector-python

from flask import Flask,request,redirect,url_for,render_template
import mysql, MySQLdb, mysql.connector

# CONNECTION
DB = mysql.connector.connect(
  host="localhost", 
  port="3306",
  user="username",
  password="password",
  database="database",
  auth_plugin='mysql_native_password'
  )

# EXAMPLE INSERT INTO table users
conexao = DB.cursor()

SQL_COMMAND = "INSERT INTO users(name, email) VALUES (%s, %s)"
VAL = [
  ('MAURICIO', 'P'),
  ('NETO', 'N'),
  ('ARIEL', 'A')
]

conexao.executemany(SQL_COMMAND, VAL) 

DB.commit()

conexao.close()

DB.close()

if __name__ == "__main__":
    app.run(debug=True)
Perroni
  • 19
  • 7
  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Apr 18 '20 at 15:55