gogoWebsite

flask connects to MySQL database

Updated to 2 days ago

Flask connects MySQL data. Novice recommends using pymysql to reduce the chance of errors

Download the driver package pymysql, use commands to install in the terminal, the installation command is as follows

pip install pymysql

Install the flask_sqlalchemy package, making flask more convenient when using sqlalchemy

pip install flask-sqlalchemy

Connect to Mysql

Create a new flask project and write it in
Import module SQLAlchemy

from flask_sqlalchemy import SQLAlchemy

Create a SQLAlchemy instance object, named db, pass the flask instance object app as a parameter to SQLAlchemy, associate db and app, and call its related functions

db = SQLAlchemy(app)

2. Configure database information in python

# MySQL host name, default 127.0.0.1
 HOSTNAME = "127.0.0.1"
 # MySQL listening port number, default 3306
 PORT = 3306
 # Connect to MySQL username and set it yourself
 USERNAME = "root"
 # Connect MySQL password and set it yourself
 PASSWORD = "root"
 # The database name created on MySQL
 DATABASE = "database_learn"
 # Modify the following code to operate different SQLs is much simpler than writing native SQL --》 Through ORM, you can change the SQL used from the underlying layer.
 ['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"

Create a database and test connections using the database tool

with app.app_context():
    with () as conn:
        result = ("select 1")
        print(())  # (1,)

Return (1,), the connection is successful
The complete code block is as follows

from flask import Flask
 from flask_sqlalchemy import SQLAlchemy

 app = Flask(__name__)

 # MySQL hostname
 HOSTNAME = "127.0.0.1"
 # MySQL listening port number, default 3306
 PORT = 3306
 # Connect to MySQL username and set it yourself
 USERNAME = "root"
 # Connect MySQL password and set it yourself
 PASSWORD = "password"
 # The database name created on MySQL
 DATABASE = "datebase_learn"
 # Modify the following code to operate different SQLs is much simpler than writing native SQL --》 Through ORM, you can change the SQL used from the underlying layer.
 ['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"

 db = SQLAlchemy(app)

 # Test whether the connection is successful
 with app.app_context():
     with () as conn:
         result = ("select 1")
         print(()) # (1,)

 @('/')
 def hello_world(): # put application's code here
     return 'Hello World!'

 if __name__ == '__main__':
     ()

Error message

Error prompt: Not an executable object: ‘select 1’
The following code prompts an error

db=SQLAlchemy(app)
with app.app_context():
    with () as conn:
        result = ("select 1")
        print(())

Reason: 'select 1' is not an executable object
Solution:
The execution of text SQL requires the use of text() method in sqlalchemy to process strings and then execute statements
1. Import module

from sqlalchemy import text

2. Modify the key code
Willresult = ("select 1")
Modify to the following code

result = (text("select 1"))