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__ = 'user'
# 表的结构:
id = Column(String(20),primary_key=True)
name = Column(String(20))
std_class = Column(String(20))
def __init__(self, id, name, std_class):
self.id = id
self.name = name
self.std_class = std_class
加库后面加 ?charset=utf8
engine = create_engine('mysql+mysqldb://root:123@localhost:3306/test?charset=utf8')
解决了存储到数据库中文乱码的问题
DBSession = sessionmaker(bind=engine)
session = DBSession()
new_user = USer(name='Bob')
添加到session:
session.add(new_user)
提交即保存到数据库:
session.commit()
关闭session:
session.close()