💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
- 安装 >pip install mysql-connector >pip install sqlalchemy >https://docs.sqlalchemy.org/en/latest/orm/tutorial.html#working-with-related-objects - 测试 > import sqlalchemy > sqlalchemy.__version__ - 创建模型mysql_orm.py ``` from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime, Boolean # MySQLDB不支持python3,所以这里要使用mysqlconnector engine = create_engine('mysql+mysqlconnector://root:admin@localhost:3306/mydb?charset=utf8') Base = declarative_base() Session = sessionmaker(bind=engine) """ 用户表 """ class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) #主键 uname = Column(String(50), nullable=False) #不能为空 pwd = Column(String(50), nullable=False) created_at = Column(DateTime) is_valid = Column(Boolean) ``` - 创建数据库mydb - 生成表 1. 进入当前文件python命令行 2. 引入 from mysql_orm import User 3. 引入 from mysql_orm import engine 4. 生成表 User.metadata.create_all(engine)