使用records来操作mysql
参考:知乎
基础
conda install -y records pymysql
操作
查询
import records
# 获取数据库
db = records.Database('mysql+pymysql://root:tianyunali@soft.tianyunperfect.cn:3306/test')
# 查询
rows = db.query('select * from user')
# 所有对象
print(rows.all())
# 转换为数组和字典
print(rows.all(as_dict=True))
print(rows.as_dict()[0])
print(len(rows))
DDL
# 创建表
sql_create_table = """CREATE TABLE IF NOT EXISTS lemon_user (
name varchar(20),
age int
) DEFAULT CHARSET=utf8 ;"""
db.query(sql_create_table)
插入单条数据
user = {"name": "yuze5", "age": 20}
db.query('INSERT INTO lemon_user(name,age) values (:name, :age)', **user)
插入多条数据
users = [
{"name":"yuze", "age": 13},
{"name":"yuze2", "age": 15},
{"name":"yuze3", "age": 16}
]
db.bulk_query('INSERT INTO lemon_user(name,age) values (:name, :age)', users)
事务支持
with db.transaction() as tx:
user = {"name": "yuze9", "age": 20}
tx.query('INSERT INTO lemon_user(name,age) values (:name, :age)', **user)
# 下面是错误的 sql 语句,有错误,则上面的 sql 语句不会成功执行。
tx.query('sof')
数据导出为json
支持: json, yaml, xls, xlsx, pandas, html
rows = db.query('SELECT * FROM lemon_user;')
json_rows = rows.export('json')
print(json_rows)
数据导出为excel
rows = db.query('SELECT * FROM lemon_user;')
with open('users.xlsx', 'wb') as f:
f.write(rows.export('xlsx'))