from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy import text app = Flask(__name__) # 主机IP地址 HOSTNAME = "127.0.0.1" # MySql的监听端口号,默认3306 PORT = 3306 # 用户名,密码,自己设置的 USERNAME = "root" PASSWORD = "root" # MySql上创建的数据库名称. DATABASE = "database_learn" app.config['SQLALCHEMY_DATABASE_URI'] = \ f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8" # 在app.config中设置好连接数据库信息. # 然后使用SQLAlchemy(app)创建db对象,SQLAlchemy就会自动读取app.config中设置的连接信息. # 读取的就是上面这个设置的地方app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # 测试连接是否成功! # 涉及到Flask上下文的问题,所以需要加上with app.app_context(). with app.app_context(): with db.engine.connect() as conn: # 注意这里需要加上text(),不然会报错 # sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: 'select 1 from dual' # 需要导入from sqlalchemy import text ret = conn.execute(text("select 1 from dual")) # 正常的话的应该返回(1,) print(ret.fetchone()) @app.route("/") def hello_world(): return "hello world!" if __name__ == "__main__": app.run(host="0.0.0.0", port=5001, debug=True)
效果:连接成功
标签:__,sqlalchemy,text,app,连接,MySql,import,数据库 From: https://www.cnblogs.com/pythonex/p/18088271