1. 使用豆瓣源安装包所需模块
pip install SQLAlchemy -i https://pypi.doubanio.com/simple
pip install pymysql -i https://pypi.doubanio.com/simple
https://www.cnblogs.com/DragonFire/p/10166527.html
2.在项目中创建文件create_table.py
导入并实例化一个 基类
# 1.导入SQLAlchemy的基本类
from sqlalchemy.ext.declarative import declarative_base
# 2.创建ORM模型基类
Base = declarative_base() # Django 的 Model
# 3.导入ORM对应的数据库类型的字段
from sqlalchemy import Column,Integer,String # 列 int varchar
3 创建表
单表
class User(Base):
__tablename__ = "user"
id = Column(Integer,primary_key=True,autoincrement=True) # int 主键 自增
name = Column(String(32),index=True) # varchar(32) 创建索引
-
外键
Foreignkey关系
from sqlalchemy.orm import relationship # 表关系
class Student(Base):
__tablename__ = 'student'
id = Column(Integer, primary_key=True)
name = Column(String(32))
School_id = Column(Integer,ForeignKey("school.id")) # 数据表的id
# Student.stu2sch 转到 School表中
stu2sch = relationship("School",backref="sch2stu") # 创建外键关系 反向关系 学生对学校 反向学校对学生
class School(Base):
__tablename__ = "school"
id = Column(Integer, primary_key=True)
name = Column(String(32))
-
多对多
ManyToMany关系
class Girls(Base):
__tablename__ = "girl"
id = Column(Integer,primary_key=True)
name = Column(String(32))
# 创建关系
girl2boy = relationship("Boys",secondary='hotel',backref="boy2girl") # 对象名 关联hotel表 不是表明
class Boys(Base):
__tablename__ = "boy"
id = Column(Integer, primary_key=True)
name = Column(String(32))
class Hotel(Base):
__tablename__ = "hotel"
id = Column(Integer, primary_key=True)
girl_id = Column(Integer, ForeignKey("girl.id"))
boy_id = Column(Integer, ForeignKey("boy.id"))
4.创建数据库链接
from sqlalchemy import create_engine
"""
# mysql数据库 + pymysql驱动 :// 用户名:密码@主机IP:端口/数据库名?字符集
"""
engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/sqlalchemy?charset=utf8")
# 6.去数据库中创建与User所对应的数据表
Base.metadata.create_all(engine) # 创建所有继承Base类对象表
-
注意
可能报错 无需理会
Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 485")
result = self._query(query)