Using MySQL in Flask

前端 未结 8 757
忘掉有多难
忘掉有多难 2020-12-02 11:46

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 muc

相关标签:
8条回答
  • 2020-12-02 11:57
    #!/usr/bin/python
    from flask import Flask,jsonify,abort, make_response
    import MySQLdb
    
    app = Flask(__name__)
    
    db = MySQLdb.connect("localhost", "root", "yourDbPassWord", "DBname")
    
    @app.route('/api/v1.0/items', methods=['GET'])
    def get_items():
        curs = db.cursor()
        try:
            curs.execute("SELECT * FROM items")
            ...
    
        except:
            print "Error: unable to fetch items"
        return jsonify({"desired: " response})
    
    0 讨论(0)
  • 2020-12-02 12:00

    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()
    
    0 讨论(0)
  • 2020-12-02 12:05

    Pretty simple with pymysql:

    from flask import Flask, request, render_template
    import pymysql
    
    db = pymysql.connect("localhost", "username", "password", "database")
    
    app = Flask(__name__)
    api = Api(app)
    
    @app.route('/')
    def someName():
        cursor = db.cursor()
        sql = "SELECT * FROM table"
        cursor.execute(sql)
        results = cursor.fetchall()
        return render_template('index.html', results=results)
    
    if __name__ == '__main__':
    app.run(debug=True)
    

    In your index.html file just do something like:

    <div>
    <% for row in results %}
          <tr>
             <td>{{ row[0] }}</td>
             <td>{{ row[1] }}</td>
             <td>{{ row[2] }}</td>
             <td>{{ row[3] }}</td>
          </tr>
    {% endfor %}
    </div>
    
    0 讨论(0)
  • 2020-12-02 12:15

    Just add pymysql to your app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@server/db'

    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@server/db'
    

    All the best.

    0 讨论(0)
  • 2020-12-02 12:17

    Easy with Mysql,

    1. Create db with following command

      CREATE TABLE MyUsers ( firstname VARCHAR(30) NOT NULL,  lastname VARCHAR(30) NOT NULL);
      
    2. Copy paste below code in app.py file

      from flask import Flask, render_template, request 
      from flask_mysqldb import MySQL
      
      app = Flask(__name__)
      
      
      app.config['MYSQL_HOST'] = 'localhost'
      app.config['MYSQL_USER'] = 'root'
      app.config['MYSQL_PASSWORD'] = 'root'
      app.config['MYSQL_DB'] = 'MyDB'
      
          mysql = MySQL(app)
      
      
      @app.route('/', methods=['GET', 'POST'])
      def index():
          if request.method == "POST":
              details = request.form
              firstName = details['fname']
              lastName = details['lname']
              cur = mysql.connection.cursor()
              cur.execute("INSERT INTO MyUsers(firstName, lastName) VALUES (%s, %s)", (firstName, lastName))
              mysql.connection.commit()
              cur.close()
              return 'success'
          return render_template('index.html')
      
      
      if __name__ == '__main__':
             app.run()
      
    0 讨论(0)
  • 2020-12-02 12:18

    mysql version: 5.7

    Using mysql-connector. To install mysql-connector package in python3.

    python3 -m pip install mysql-connector
    

    To Connect with your database and querying, use following lines of code in your python script:

    import mysql.connector
    
    database=mysql.connector.connect(host='localhost',user='user',passwd='password',datbase='dbname')
        cursor=database.cursor()
        query="select * from test_table"
        cursor.execute(query)
        database.commit()
    
    0 讨论(0)
提交回复
热议问题