欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python连接SQLAlchemy

程序员文章站 2024-03-02 19:53:34
...

SQLAlchemy安装

pip install pymysql
pip install SQLAlchemy

连接数据库

from sqlalchemy import create_engine

HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "test_sql"
USERNAME = "root"
PASSWORD = "root"

DB_URI = "mysql+pymysql://{username}:{password}@{host}:{post}/{db}?charset=utf8".format(username=USERNAME, password=PASSWORD, host=HOST, post=PORT, db=DATABASE)

# 创建数据库引擎
engine = create_engine(DB_URI)

# 判断是否连接成功
conn = engine.connect()
result = conn.execute("select 1")
print(result.fetchall())
  • 如果出现警告
    python连接SQLAlchemy
  • 解决办法
    安装mysql-connector-python驱动
pip install mysql-connector-python

修改代码

engine = create_engine("mysql+pymysql://root:[email protected]/my_db")

改为:

engine = create_engine("mysql+mysqlconnector://root:[email protected]/my_db")
  • 完整代码
from sqlalchemy import create_engine

HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "test_sql"
USERNAME = "root"
PASSWORD = "root"

DB_URI = "mysql+mysqlconnector://{username}:{password}@{host}:{post}/{db}?charset=utf8".format(username=USERNAME, password=PASSWORD, host=HOST, post=PORT, db=DATABASE)

# 创建数据库引擎
engine = create_engine(DB_URI)

# 判断是否连接成功
conn = engine.connect()
result = conn.execute("select 1")
print(result.fetchall())
相关标签: flask