sqlalchemy中让MySQL支持中文字符
engine = create_engine("mysql+pymysql://root:mysql8@localhost/mysqltest?charset=utf8", encoding='utf-8')
import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import func # 建立连接。通过pymysql执行原生SQL,加echo打印出信息,不加就不打印 engine = create_engine("mysql+pymysql://root:mysql8@localhost/mysqltest", encoding='utf-8',) #echo=True) # 生成ORM基类 Base = declarative_base() # 表对象继承基类 class User(Base): __tablename__ = 'user' # 表名 id = Column(Integer, primary_key=True) name = Column(String(32)) password = Column(String(64)) def __repr__(self): return "<id:%s name:%s> " % (self.id, self.name) # 创建表结构,创建每个表都继承这个类。一执行可以把所有都创建完 Base.metadata.create_all(engine) ''' 表创建完了,现在来创建一条数据 ''' # 创建与数据库的Session_class类 Session_class = sessionmaker(bind=engine) # 生成session实例,类似于cursor session = Session_class() # 生成要创建的数据对象 user_obj = User(name="alex", password="alex3714") user_obj1 = User(name="jack", password="jack1234") print(user_obj.name,user_obj.password, user_obj.id) # 加入到session session.add(user_obj) session.add(user_obj1) print(user_obj.name, user_obj.password, user_obj.id) # 提交,创建数据 session.commit() print(user_obj.name, user_obj.password, user_obj.id) ''' 现在查询name="alex"的所有数据放在对象列表, 打印的地址,加个repr方法可以打印格式化数据 filter_by和filter随便,哪个管用就哪个 ''' data = session.query(User).filter_by(name="alex").filter_by(id=1).all() print(data) ''' 修改 ''' data[0].name = "Alex Li" data[0].password = "1234567" session.commit() print(session.query(User).filter_by(id=1).all()) # ''' # 回滚 # ''' # fake_user = User(name='Rain', password='12345') # session.add(fake_user) # # 这时看session里有你刚添加和修改的数据 # print(session.query(User).filter(User.name.in_(['Jack', 'rain'])).all()) # # 此时你rollback一下 # session.rollback() # # 再查就发现刚才添加的数据没有了。 # print(session.query(User).filter(User.name.in_(['Jack', 'rain'])).all()) # # Session # # Session.commit() ''' 统计 ''' count = session.query(User).filter(User.id>0).count() print(count) ''' 分组,统计每个名字出现的次数 ''' result = session.query(User.name, func.count(User.name)).group_by(User.name).all() print(result) ''' 删除数据 ''' session.delete(session.query(User).filter_by(id=1).first()) session.commit() print(session.query(User).all()) '''打印结果: alex alex3714 None alex alex3714 None alex alex3714 1 [<id:1 name:alex> ] [<id:1 name:Alex Li> ] 2 [('Alex Li', 1), ('jack', 1)] [<id:2 name:jack> ] '''