web程序中使用数据库存储数据,在视图函数中操作数据库。如果在视图函数中编写SQl语句,则代码显得太混乱,所以开发者 将数据库中的table映射成python类,将column映射成类的属性,row映射成类的实例,所以就可以通过操作python类对象实现对数据库的操作。
一、连接数据库
数据库的连接是在SQLALCHEMY_DATABASE_URI中完成的。
常用的有:
mysql的uri为:‘mysql://username:password@host/databasename’
sqlite的uri为:‘sqlite:///’+os.path.join(app_root_path,’.database’)
二、建表
table在映射为类,所以建表就是定义类
class User(db.Model):
id=db.Column(db.Integer,primary_key=True)
SQLAlchemy常用的字段类型有Integer,String,Text,Time,Data,DataTime,Boolean,Float
三、数据库的操作
数据库的基本操作CRUD,
Create:
user=User(name=‘zhang’)
db.session.add(user)
db.session.commit()
Read:
<Model类>.query.<过滤方法>.<查询方法>(也可以不过滤,直接查询)
常用的过滤方法:
filter() filter是最基本的过滤方式,它使用指定的规则来过滤记录。如User.query.filter(User.name==‘zhang’).all()
filter_by() filter_by()比filter()更好用,因为直接使用字段名称,可以使用各种表达式。 User.query.filter——by(name=‘zhang’ and telnum=‘19987657767’).all()
order_by() 根据指定规则进行排序,返回结果
limit(limit)
group_by()
offset(offset)
常用的查询方法:
all();
first();
one()(只允许有一条记录,如果记录数不等于1.则抛出错误)
get(id);
count()(返回查询结果的数量);
one_or_none(如果 结果不为1,不抛出错误,而是返回none
first_or_404();
get_or_404(id);
paginate()(返回一个pagination对象,可以对记录进行分页处理);with_parent(instance)(传入模型类实例作为参数,返回和这个实例相关联的对象)
Update
user=User.query.get(3)
user.name=‘zhangyuanbin’
db.session.commit()
Delete
user=User.query.get(3)
db.session.delete(user)
db.session.commit()
四、定义关系(重难点)
没有关系,各个表就是一张张死表。通过建立关系,可以让不同表之间的字段建立联系。
1.一对多关系;多的 一侧设置 外键
class Writer(db.Model):
books=db.relationship(‘Book’,back_populates=‘writer’)
class Book(db.Model):
writer_id=db.Column(db.Integer,db.ForeignKey(‘writer.id’))
writer=db.relationship(‘Writer’,back_populations=‘books’)
2.一对一关系;设置一个外键,也不用back-populations,因为一对一,对应的关系只能是它。
class Country(db.Model):
capital=db.relationship(‘Capital’,uselist=False)
class Capital(db.Model):
country_id=db.Column(db.Integer,db.ForeignKey(‘country.id’))
country=db.relationship(‘Country’)
3.多对多关系
association_table=db.Table(‘association’,db.Column(‘student_id’,db.Integer,db.ForeignKey(‘student.id’)),db.Column(‘teacher_id’,db.Integer,db.ForeignKey(‘teacher.id’)))
class Student(db.Model):
teachers=db.relationship(‘Teacher’,secondary=association_table,back_populates=‘students’)
class Teacher(db.Model):
students=db.relationship(‘Student’,secondary=association_table,back_populates=‘teachers’)
多对多关系是两个一对多关系的合成。在 关联表association_table中有两个外键,分别为两张表的ID 字段。secondary=association_table,back_populates=’’
students_id | teachers_id |
---|---|
1 | 1 |
1 | 2 |
2 | 4 |
1 | 3 |
2 | 3 |
2 | 1 |
1 | 4 |
students一对多association_table(students_id)一对一(teachers_id)
teachers一对多association_table(teachers_id)一对一(students_id)
通过association_table这个‘中间人’,利用两个一对多,实现了多对多。