1、安装sqlalchemy
pip install sqlalchemy
2、导入必要的包及模块
import
sqlalchemy
from
sqlalchemy
.
ext
.
declarative
import
declarative_base
from
sqlalchemy
.
orm
import
sessionmaker
3、创建数据库连接实例
#创建数据库连接实例(#"数据库类型+数据库模块://用户名:密码@主机/库名")
db
=
sqlalchemy
.
create_engine
(
"mysql+pymysql://root:q1q1q1@localhost/a"
)
4、创建一个元类的继承类
base
=
declarative_base
(
db
)
5、定义一个表(使用类)继承base
class
Student
(
base
)
:
__tablename__
=
"student"
id
=
sqlalchemy
.
Column
(
sqlalchemy
.
Integer
,
primary_key
=
True
)
name
=
sqlalchemy
.
Column
(
sqlalchemy
.
String
(
32
)
)
age
=
sqlalchemy
.
Column
(
sqlalchemy
.
String
(
32
)
)
6、创建表
base.metadata返回sqlalchemy.schema.MetaData对象,它是所有Table对象的集合,调用create_all()该对象会触发CREATE TABLE语句,如果数据库还不存在这些表的话。
if
__name__
==
"__main__"
:
base
.
metadata
.
create_all
(
db
)
7、绑定连接并创建session
cursor
=
sessionmaker
(
bind
=
db
)
#得到的时一个类
session
=
cursor
(
)
#实例
8、增(插入数据)
①插入一条数据
stu
=
Student
(
id
=
1
,
name
=
"张1"
,
age
=
18
)
session
.
add
(
stu
)
session
.
commit
(
)
session
.
add_all
(
[
Student
(
id
=
2
,
name
=
"张2"
,
age
=
19
)
,
Student
(
id
=
3
,
name
=
"张3"
,
age
=
20
)
]
)
session
.
commit
(
)
9、查询
①查询所有数据
all_data
=
session
.
query
(
Student
)
.
all
(
)
#得到的是一个可迭代对象
for
data
in
all_data
:
print
(
"id:%s__name:%s__age:%s"
%
(
data
.
id
,
data
.
name
,
data
.
age
)
)
②根据条件查询多条数据
many_data
=
session
.
query
(
Student
)
.
filter_by
(
age
=
18
)
print
(
many_data
)
#实际是一个sql查询语句,其还是一个存储一个对象的带迭代内容
for
data
in
many_data
:
print
(
"id:%s__name:%s__age:%s"
%
(
data
.
id
,
data
.
name
,
data
.
age
)
)
many_data
=
session
.
query
(
Student
)
.
filter_by
(
age
=
18
)
data
,
=
many_data
print
(
"id:%s__name:%s__age:%s"
%
(
data
.
id
,
data
.
name
,
data
.
age
)
)
③查询一条数据
data
=
session
.
query
(
Student
)
.
get
(
ident
=
3
)
#查一条,只能以主键查
print
(
"id:%s__name:%s__age:%s"
%
(
data
.
id
,
data
.
name
,
data
.
age
)
)
10、删除
#先查询一条
data
=
session
.
query
(
Student
)
.
get
(
ident
=
3
)
#然后删除
session
.
delete
(
data
)
#然后提交操作
session
.
commit
(
)
11、修改
# 先查询一条
data
=
session
.
query
(
Student
)
.
get
(
ident
=
2
)
#然后删除
data
.
name
=
"老李头"
#然后提交操作
session
.
commit
(
)