原标题:Dataset基于SQLAlchemy的便利工具
作者: w2n1ck
数据集使得数据库中的数据读取和写入数据就像阅读和编写JSON文件一样简单。
dataset对于操作JSON、CSV文件、NoSQL非常好用。
import dataset
连接MySQL数据库:
db = dataset.connect('mysql://username:password@10.10.10.10/ctf?charset=utf8')用户名:username,密码:password,数据库地址(地址+端口):10.10.10.10,database名: ctf连接SQLite数据库:db = dataset.connect('sqlite:///ctf.db')连接PostgreSQL数据库:db = dataset.connect('postgresql://scott:tiger@localhost:5432/mydatabase')
一定要注意指定字符编码
table = db['city'] #(选择city表)user = table('name') # 找出表中'name'列属性所有数据res = db.query('select name from table limit 10') # 如果不需要查看全部数据的话最好用limit,因为全部数据的载入非常非常耗时间for x in res:print x['name'] # 选name字段的数据table.insert(dict(name='John Doe', age=37))table.insert(dict(name='Jane Doe', age=34, gender='female'))john = table.find_one(name='John Doe')
在数据库中查找是否有同时满足多个条件的数据:table.find_one(属性1=属性值1, 属性2=属性值2, …)
注:find_one速度很慢
插入数据
dataset会根据输入自动创建表和字段名
table = db['user']# 或者table = db.get_table('user')table.insert(dict(name='John Doe', age=46, country='China'))table.insert(dict(name='Jane Doe', age=37, country='France', gender='female'))# 主键id自动生成
更新数据
table.update(dict(name='John Doe', age=47), ['name'])# 第二个参数相当于sql update语句中的where,用来过滤出需要更新的记录
事务操作
事务操作可以简单的使用上下文管理器来实现,出现异常,将会回滚
with dataset.connect() as tx:tx['user'].insert(dict(name='John Doe', age=46, country='China'))# 相当于:db = dataset.connect()db.begin()try:db['user'].insert(dict(name='John Doe', age=46, country='China'))db.commit()except:db.rollback()# 也可以嵌套使用:db = dataset.connect()with db as tx1:tx1['user'].insert(dict(name='John Doe', age=46, country='China'))with db as tx2:tx2['user'].insert(dict(name='Jane Doe', age=37, country='France', gender='female'))
从表获取数据
users = db['user'].all()for user in db['user']:# print(user['age'])# chinese_users = user.find(country='China')john = user.find_one(name='John Doe')
获取非重复数据
db['user'].distinct('country')
删除记录
table.delete(place='Berlin')
执行SQL语句
result = db.query('SELECT country, COUNT(*) c FROM user GROUP B