mysql dataset 用法_Dataset基于SQLAlchemy的便利工具

本文介绍了如何使用dataset库简化MySQL数据库的读写操作,包括连接数据库、查询数据、插入与更新记录、事务处理等。此外,还讨论了JSON、Python装饰器、Flask框架和MySQL的使用技巧,如错误处理、日志记录及字符编码设置。
摘要由CSDN通过智能技术生成

原标题:Dataset基于SQLAlchemy的便利工具

b017e1f58ee7784d82d1c6f48e3d8c91.png

作者: 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值