廖雪峰 SQLalchemy 代码执行不通的问题

黄磊
2023-12-01

1、首先确保安装了 mysql-connector 模块

    pip install mysql-connector

2、将

engine = create_engine('mysql+mysqlconnector://root:888@localhost:3306/awesome')

 改成:

engine = create_engine('mysql+pymysql://root:888@localhost:3306/awesome')

3、源码:

# 导入:
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 创建对象的基类:
Base = declarative_base()

# 定义User对象:
class User(Base):
    # 表的名字:
    __tablename__ = 'users'

    # 表的结构:
    id = Column(String(20), primary_key=True)
    name = Column(String(20))

# 初始化数据库连接:
engine = create_engine('mysql+pymysql://root:888@localhost:3306/awesome')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)

 

 类似资料: