Flask Modules - How to connect to MySQL

Establish a connection between Pycharm and MySQL.


# Configure the "SQLALCHEMY_DATABASE_URI" argument with all the required information.
# This argument is used to specify the SQLAlchemy database connection URI.
# Here, we construct the database connection URI as a MySQL connection string,
# including the username, password, hostname, port, database name, and character set 
# setting.

app.config['SQLALCHEMY_DATABASE_URI'] = 
f"mysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"


# Utilize 'SQLAlchemy' to alias 'app' as 'db'.

db = SQLAlchemy(app)


# Create an application context using app.app_context()
# Establish a connection to the database using db.engine.connect()
# Execute a SQL query "select 1"
# Fetch and print the first result row

with app.app_context():
    with db.engine.connect() as conn:
        rs = conn.execute(text("select 1"))   
        print(rs.fetchone())

猜你喜欢

转载自blog.csdn.net/Alexandra_Zero/article/details/132602047