orm 是面向对象数据库,可有效避免写sql语句繁琐,最近了解一下感觉很不错,后面 贴代码,连接数据库我是使用 mysqlconnector库,在你的pycharm里面安装这个包,然后 打开数据 :net start mysql,用命令行创建数据库,创建表就可以orm了( tablename = ‘users’),创建了 users表,MySqlManager 是来测试数据库操作的,习惯使用面向对象来做一些demo,代卖注释很详细
import random
from sqlalchemy import create_engine, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import ForeignKey
from sqlalchemy import Column, String, Integer, Text
from sqlalchemy.orm import sessionmaker, relationship
# https://www.cnblogs.com/ray-mmss/p/9424978.html
Base = declarative_base()
class MySqlManager(object):
def __init__(self):
self.engine = create_engine('mysql+mysqlconnector://root:123@localhost/test',
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
self.create_all()
# 根据引擎创建session工厂
self.SessionFactory = sessionmaker(bind=self.engine)
# 用session工厂创建一个session对象
self.session = self.SessionFactory()
# 根据Users类对users表进行增删改查
# 添加数据
def add_datas(self):
obj1 = Student(username='bob0',password='123',email='bobbob32@123.com')
obj2 = Student(username='bob1', password='135', email='bob2@123.com')
# self.session.add(obj1)
self.session.add_all([obj1,obj2])
self.session.commit()
# 删除数据库
def delete_datas(self):
self.session.query(Student).filter(Student.username == 'bob123').delete()
self.session.commit()
#修改数据库
def update_datas(self):
self.session.query(Student).filter(Student.id == 6).\
update({Student.username :'bob123'})
self.session.query(Student).filter(Student.id == 7).\
update({Student.username : 'bob456'})
self.session.query(Student).filter(Student.id==9).\
update({Student.username:Student.username+"HUB"},synchronize_session=False)
self.session.commit()
#查询数据
def search_datas(self):
result = self.session.query(Student).all()
for row in result:
print(row.id,row.username,row.password,row.email)
# result = self.session.query(Student).filter(Student.id >= 1)
# for row in result:
# print(row.id, row.username, row.password, row.email)
#
# result = self.session.query(Student).filter(Student.id >= 1).first
# print(result)
# 关闭数据库
def closeSession(self):
# 关闭session
self.session.close()
def create_all(self):
Base.metadata.create_all(self.engine)
def drop_all(self):
Base.metadata.drop_all(self.engine)
class Student(Base):
__tablename__ = 'users'
id = Column(Integer,primary_key=True)
username = Column(String(64),nullable=False,index=True)
password = Column(String(64),nullable=False)
email = Column(String(64),nullable=False,index=True)
def __repr__(self):
return '%s(%r)'%(self.__class__.__name__,self.username)