Python编程:records库操作SQL查询MySQL数据库

版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/83587658

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

猜你喜欢

转载自blog.csdn.net/mouday/article/details/83587658