records库可以快速的查询数据库,比操作游标cursor对象要好使,还支持导出为具体格式
支持:RedShift, Postgres, MySQL, SQLite, Oracle, and MS-SQL
不过作者没有写清楚依赖包,所以遇到一点点问题,好在顺利解决
项目地址:https://github.com/kennethreitz/records
安装
pip install records mysqlclient
示例
以下是查询mysql数据库数据示例:
import records
db = records.Database('mysql://root:123456@localhost/demo?charset=utf8')
rows = db.query("select * from names")
for row in rows:
print(row.id, row.name, row.age)
"""
2 大红 24
3 大壮 24
4 秀英 24
6 小明 23
7 大名 23
10 壮壮 25
"""
"""
mysql> select * from names;
+----+--------+------+
| id | name | age |
+----+--------+------+
| 2 | 大红 | 24 |
| 3 | 大壮 | 24 |
| 4 | 秀英 | 24 |
| 6 | 小明 | 23 |
| 7 | 大名 | 23 |
| 10 | 壮壮 | 25 |
+----+--------+------+
"""
# 转为json
print(rows.as_dict())
# 导出为具体格式,支持: csv、yaml、json、xls、df(DataFrame)
print(rows.export("json"))
# 转为表格形式
print(rows.dataset)
使用sqlalchemy实现的,所以链接方式可以参考sqlalchemy
链接方式:
SQLite: sqlite:///users.db
MySQL: mysql://user:password@host/database