博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 之路 13 ORM SQLAlchemy
阅读量:4965 次
发布时间:2019-06-12

本文共 5469 字,大约阅读时间需要 18 分钟。

 

1. 安装

# pip install sqlalchemy
# pip install pymysql

2. 创建引擎

>>> from sqlalchemy import create_engine
>>> engine = create_engine('mysql+pymysql://USERNAME:PASSWORD@DB_HOST:DB_PORT/DB_NAME', pool_recycle=3600)
pool_recycle 指定连接池收回时间。

引擎初始化后,就可以连接了。

3. 连接数据库

 

>>> connection = engine.connect()

4. metadata

>>> from sqlalchemy import MetaData
>>> metadata = MetaData()

5. 定义表

>>> from sqlalchemy import Table, Column, Integer, Numeric, String, ForeignKey, DateTime      
>>> from datetime import datetime                                                             
>>> users = Table('users', metadata,
...     Column('user_id', Integer(), primary_key=True),
...     Column('username', String(15), nullable=False, unique=True),
...     Column('email_address', String(255), nullable=False),
...     Column('phone', String(20), nullable=False),
...     Column('password', String(25), nullable=False),
...     Column('created_on', DateTime(), default=datetime.now),
...     Column('updated_on', DateTime(), default=datetime.now, onupdate=datetime.now)
... )

6. 创建表

>>> metadata.create_all(engine)

7. 插入数据

>>> ins = users.insert().values(

... user_id=8888,
... username='111cn.net ',
... email_address = 'support@111cn.net ',
... phone = 12345678901,
... password = 'www.111cn.net '
... )
>>> print ins
INSERT INTO users (user_id, username, email_address, phone, password, created_on, updated_on) VALUES (:user_id, :username, :email_address, :phone, :password, :created_on, :updated_on)
>>> ins.compile().params
{'username': '111cn.net ', 'user_id': 8888, 'phone': 12345678901, 'created_on': None, 'updated_on': None, 'password': 'www.111cn.net ', 'email_address': 'support@111cn.net '}

8. 执行

>>> result = connection.execute(ins)
>>> result.inserted_primary_key
[8888]

9. 插入多条

>>> ins = users.insert()

>>> multi_data = [
... {
... 'user_id':1,
... 'username':'u1',
... 'email_address':'u1@111cn.net ',
... 'phone' : 12345678901,
... 'password': 'www.111cn.net '
... },
... {
... 'user_id':2,
... 'username':'u2',
... 'email_address':'u2@111cn.net ',
... 'phone' : 12345678901,
... 'password': 'www.111cn.net '
... }
... ]
>>> result = connection.execute(ins, multi_data)
>>> result.rowcount
2

10. 查询

>>> from sqlalchemy import 
>>> s = select([users])
>>> print str(s)
SELECT users.user_id, users.username, users.email_address, users.phone, users.password, users.created_on, users.updated_on 
FROM users
>>> rp = connection.execute(s)
>>> results = rp.fetchall()
>>> print results
[(1, 'u1', 'u1@111cn.net ', '12345678901', 'www.111cn.net ', datetime.datetime(2016, 6, 22, 11, 26, 5), datetime.datetime(2016, 6, 22, 11, 26, 5)), (2, 'u2', 'u2@111cn.net ', '12345678901', 'www.111cn.net ', datetime.datetime(2016, 6, 22, 11, 26, 5), datetime.datetime(2016, 6, 22, 11, 26, 5)), (8888, '111cn.net ', 'support@111cn.net ', '12345678901', 'www.111cn.net ', datetime.datetime(2016, 6, 22, 11, 13, 32), datetime.datetime(2016, 6, 22, 11, 13, 32))]

>>> first_row = results[0]
>>> print first_row
(1, 'u1', 'u1@111cn.net ', '12345678901', 'www.111cn.net ', datetime.datetime(2016, 6, 22, 11, 26, 5), datetime.datetime(2016, 6, 22, 11, 26, 5))
>>> first_row[1]
'u1'
>>> first_row.phone
'12345678901'
>>> first_row[users.c.user_id]

>>> rp = connection.execute(s)

>>> for record in rp:         
...   print record.username   
... 
u1
u2
111cn.net

>>> s = select([users.c.user_id, users.c.username])
>>> rp = connection.execute(s)
>>> print rp.keys()
['user_id', 'username']
>>> print rp.fetchone()
(8888, '111cn.net ')
>>> print rp.fetchone()
(1, 'u1')
>>> print rp.fetchone()
(2, 'u2')
>>> print rp.fetchone()
None

11. 排序

>>> s = select([users.c.user_id, users.c.username])
>>> s = s.order_by(users.c.user_id)
>>> print str(s)
SELECT users.user_id, users.username 
FROM users ORDER BY users.user_id
>>> rp = connection.execute(s)
>>> for i in rp:
...   print ('{} - {}'.format(i.user_id, i.username)) 
... 
1 - u1
2 - u2
8888 - 111cn.net

>>> s = select([users.c.user_id, users.c.username])
>>> s = s.order_by(desc(users.c.user_id))
>>> rp = connection.execute(s)
>>> print (['{} - {}'.format(i.user_id, i.username) for i in rp])
['8888 - 111cn.net ', '2 - u2', '1 - u1']

>>> s = select([users.c.user_id, users.c.username]).where(users.c.user_id.in_([1,2]))
>>> rp = connection.execute(s)                                                       
>>> print (['{} - {}'.format(i.user_id, i.username) for i in rp])                    
['1 - u1', '2 - u2']

12. 更新

 

>>> from sqlalchemy import update

>>> u = update(users).where(users.c.username == 'u1')
>>> u = u.values(phone=00000000000)
>>> print str(u)
UPDATE users SET phone=:phone, updated_on=:updated_on WHERE users.username = :username_1
>>> result = connection.execute(u)
>>> print result
<sqlalchemy.engine.result.ResultProxy object at 0x7f6839f1a290>
>>> print result.rowcount
1
>>> s = select([users]).where(users.c.username == 'u1')
>>> result = connection.execute(s).first()
>>> print result
(1, 'u1', 'u1@111cn.net ', '0', 'www.111cn.net ', datetime.datetime(2016, 6, 22, 11, 26, 5), datetime.datetime(2016, 6, 22, 13, 51, 16))
>>> print result.keys()
['user_id', 'username', 'email_address', 'phone', 'password', 'created_on', 'updated_on']
>>> for key in result.keys():
...   print('{:>20}: {}'.format(key, result[key]))
... 
             user_id: 1
            username: u1
       email_address: u1@111cn.net 
               phone: 0
            password: www.111cn.net 
          created_on: 2016-06-22 11:26:05
          updated_on: 2016-06-22 13:51:16
13. 删除

>>> print str(u)
DELETE FROM users WHERE users.username = :username_1
>>> s = select([users]).where(users.c.username == 'u1')
>>> result = connection.execute(s).fetchall()
>>> print result
[]

 

转载于:https://www.cnblogs.com/bigjerry/p/5742708.html

你可能感兴趣的文章
PHP5.3的VC9、VC6、Thread Safe、Non Thread Safe的区别
查看>>
Android中全屏或者取消标题栏
查看>>
处理器管理与进程调度
查看>>
页面懒加载
查看>>
向量非零元素个数_向量范数详解+代码实现
查看>>
java zip 中文文件名乱码_java使用zip压缩中文文件名乱码的解决办法
查看>>
java if 用法详解_Java编程中的条件判断之if语句的用法详解
查看>>
kafka的java客户端_KAFKA Producer java客户端示例
查看>>
java -f_java学习笔记(一)
查看>>
java 什么题目好做_用java做这些题目
查看>>
java中的合同打印_比较方法违反了Java 7中的一般合同
查看>>
php 位运算与权限,怎么在PHP中使用位运算对网站的权限进行管理
查看>>
php include效率,php include类文件超时
查看>>
matlab sin函数 fft,matlab的fft函数的使用教程
查看>>
wcdma下行如何解扩解扰 matlab,WCDMA技术基础.ppt
查看>>
MySQL date_format() 函数
查看>>
mysql 时间处理
查看>>
mysql adddate()函数
查看>>
mysql addtime() 函数
查看>>
mysql 根据日期时间查询数据
查看>>