File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ from sqlalchemy import Column , String , create_engine
5+ from sqlalchemy .orm import sessionmaker
6+ from sqlalchemy .ext .declarative import declarative_base
7+
8+ # 创建对象的基类:
9+ Base = declarative_base ()
10+
11+ # 定义User对象:
12+ class User (Base ):
13+ # 表的名字:
14+ __tablename__ = 'user'
15+
16+ # 表的结构:
17+ id = Column (String (20 ), primary_key = True )
18+ name = Column (String (20 ))
19+
20+ # 初始化数据库连接:
21+ engine = create_engine ('mysql+mysqlconnector://root:password@localhost:3306/test' )
22+ # 创建DBSession类型:
23+ DBSession = sessionmaker (bind = engine )
24+
25+ # 创建session对象:
26+ session = DBSession ()
27+ # 创建新User对象:
28+ new_user = User (id = '5' , name = 'Bob' )
29+ # 添加到session:
30+ session .add (new_user )
31+ # 提交即保存到数据库:
32+ session .commit ()
33+ # 关闭session:
34+ session .close ()
35+
36+ # 创建Session:
37+ session = DBSession ()
38+ # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行:
39+ user = session .query (User ).filter (User .id == '5' ).one ()
40+ # 打印类型和对象的name属性:
41+ print ('type:' , type (user ))
42+ print ('name:' , user .name )
43+ # 关闭Session:
44+ session .close ()
You can’t perform that action at this time.
0 commit comments