1. mac 按住command键 点进去 (win 按住Ctrl键 点进去)
1.1 旧版 导包 (会有 警告)
from sqlalchemy.ext.declarative import declarative_base
1.2 新版 导包
from sqlalchemy.orm import declarative_base, sessionmaker
2. 复制engine 修改为自己的链接
3. 实现CRUD
import random
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.orm import declarative_base, sessionmaker
# 创建 ORM 基类
Base = declarative_base()
# 定义 User 模型,与数据库中的 users 表对应
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String)
email = Column(String, unique=True)
class CreateDataBase:
def __init__(self):
# 创建数据库引擎
self.engine = create_engine('sqlite:///sqlalchemy_db.db')
# 创建所有定义的表
Base.metadata.create_all(self.engine)
# 创建会话类
Session = sessionmaker(bind=self.engine)
# 创建会话对象
self.session = Session()
def add(self, name, email):
"""添加"""
# 添加一个新的用户
new_user = User(name=name, email=email)
self.session.add(new_user)
# 提交更改到数据库
self.session.commit()
def update(self, name, email, id=1, ):
"""修改"""
update_user = self.session.query(User).filter_by(id=id).first()
update_user.name = name
update_user.email = email
self.session.commit()
def delete(self, id=1):
"""删除"""
user_to_delete = self.session.query(User).filter_by(id=id).first()
self.session.delete(user_to_delete)
self.session.commit()
def read(self):
"""查询"""
# 查询所有用户
users = self.session.query(User).all()
users_filter_by = self.session.query(User).filter_by(id=1).first()
for user in users:
print(user.id, user.name, user.email)
def __del__(self):
# 关闭会话
self.session.close()
if __name__ == '__main__':
database = CreateDataBase()
# database.add(name="陈六", email=f"{random.randint(1,11)*1000}@qq.com")
# database.update(name="wq2", email="456@qq.com", id=10)
# database.delete(id=2)
database.read()
3.1 增 C
3.2 改 U
3.3 删 D