一、ORM思想介绍
1.1 什么是ORM思想:
ORM 思想
object-relation mapping
对象关系映射(将数据库中表结构映射到对象上)
1.2 ORM思想举例分析:
比如一个表名stduent中,含有id, name, age, sex, grader 字段数据,如何获取到表名stduent中字段的数据。使用元组tuple(tuple 数据不可变),列举数据如下:
stduent id, name, age, sex, grader
[
(1, 'ling', 18, 'M', 59)
(2, 'shang', 26, 'F', 88)
(3, 'ajing', 31, 'M', 94)
]
获取表字段数据方法一:
for x in student:
for y in studnet[x]:
student[x][y]
使用循环遍历可以获取,但数据量大的时候速度会很慢,不建议。
获取表字段数据方法二:
class Student(object):
def __init__(self, id, name, age, sex, grander):
self.id = id
self.name = name
self.age = age
self.sex = sex
self.grander = grander
student1 = Student('10001', 'ling', 25, 'M', 78)
student2 = Student('10001', 'hc', 18, 'M', 99)
print(student1.name)
print(student2.age)
定义每张表为一个类,若存在多张表即定义其对应表的类
需要获取某张表的字段数据,只需要打印对应类定义的字段即可,即为ORM思想。
类的属性和表字段是一 一对应的,如下表跟类的对应:
(
表 student
id, name, age, sex, grander
类 module
id, name, age, sex, grander
)
二、SQLALchemy使用
1.1 使用SQLALchemy创建表:
在mysql库中创建一个数据库:
create database sqlalchemy;
在mysql库中创建超级用户:
grant all privileges on *.* to 'hc'@'%' identified by 'hc' \c
使用python语句在sqlalchemy库中创建student表(方法一):
import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://hc:[email protected]/sqlalchemy')
print(engine) #创建mysql的连接
sql = '''create table student(
id int not null PRIMARY KEY,
name varchar(100),
age int,
address varchar(100)
);'''
cus = engine.connect() #这个跟我们上节课说的游标操作雷同的
cus.execute(sql)
cus.close() #执行完后关闭
查看表:show tables:show tables;
查看表字段:desc student;
查看表字段创建的语句:show create table student \G;
ps:
engine = create_engine(‘mysql://hc:[email protected]/sqlalchemy’)
python3中在连接语句执行后报错:# ModuleNotFoundError: No module named ‘MySQLdb’
需要写成:
engine =create_engine(‘mysql+pymysql://hc:[email protected] /sqlalchemy’)
使用python语句在sqlalchemy库中创建teacher表(方法二):
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('mysql+pymysql://hc:[email protected]/sqlalchemy')
metadata = MetaData(engine)
teacher = Table('teacher', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50), ),
Column('age', Integer),
Column('sex', String(10)),
)
metadata.create_all(engine)
1.2 使用SQLALchemy插入表数据:
首先定义一个类:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql+pymysql://hc:[email protected]/sqlalchemy')
DBsession = sessionmaker(bind=engine)
session = DBsession()
Base = declarative_base()
class Student(Base):
__tablename__ = 'student'
id = Column(Integer, primary_key=True)
name = Column(String(100))
age = Column(Integer)
address = Column(String(100))
插入到表的数据:
student1 = Student(id=1001, name='ling', age=25, address="beijing")
student2 = Student(id=1002, name='molin', age=18, address="jiangxi")
student3 = Student(id=1003, name='karl', age=16, address="suzhou")
session.add_all([student1, student2, student3])
session.commit()
session.close()
1.3 使用SQLALchemy查询数据:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from 脚本语言.Python脚本.python.第十七课.A3 import Student
engine = create_engine('mysql+pymysql://hc:[email protected]/sqlalchemy')
DBsession = sessionmaker(bind=engine)
session = DBsession()
session.query(Student)
a = session.query(Student).filter(Student.id>1001)
print(a)
for i in a:
print(i.id)
print(i.name)
print(i.age)
print(i.address)
ps:
a = session.query(Student).filter(Student.id>1001).all() #显示查出来的全部
a =session.query(Student).filter(Student.id>1001).first() #显示查出来第一个
a =session.query(Student).filter(Student.id>1001) #显示select原语句
filter和filter_by
filter_by(name=”ling”) 不能使用> < =
filter(Student.id>1001) 这个就必须使用Student.id 可以使用> < =等