Python操作数据库,使用ORM框架(Object-Relational Mapping)—AQLAlchemy.。
MYSql:为服务器端设计的数据库,能承受高并发访问,占用的内存远大于SQLite。
# encoding:utf8# Python使用ORM框架操作数据库from sqlalchemy import Column, Integer, String, create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()class User(Base): """ CREATE TABLE purus.operation_log ( id int NOT NULL AUTO_INCREMENT, name varchar(20) NOT NULL, age varchar(100) NOT NULL, PRIMARY KEY (id) ) DEFAULT CHARSET=utf8; """ __tablename__ = 'user' # 表名 id = Column(Integer, primary_key=True) # 表结构 name = Column(String) age = Column(String)engine = create_engine('mysql+mysqlconnector://root:11111@localhost:3306/test') # 初始化数据库连接:DB_Session = sessionmaker(bind=engine) # 创建DBSession类型:# 增session = DB_Session() # 创建session对象:user = User(id='1', name='xilming', age='18') # 创建新User对象:session.add(user) # 添加到session:session.commit() # 提交即保存到数据库:session.close() # 关闭session:# 查session = DB_Session()user_info = session.query(User).filter(User.id == '1').one()print(user_info.name)session.close()# 改session = DB_Session()session.query(User).filter(User.id == '1').update({'name': 'xinxin'})session.commit()session.close()# # 删session = DB_Session()session.query(User).filter(User.id == '1').delete()session.commit()session.close()