简体   繁体   中英

Flask MySQL online Database

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...

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' 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM