Python 之records教程

Python 之records教程

一、安装

pip install records

二、初始化

import records

# 初始化db 连接 , 支持从 环境变量 DATABASE_URL 读取 url
#  数据库类型 + 数据库驱动名://用户名:密码@ip:端口/数据库名
db = records.Database("mysql+pymysql://root:mysql_EEnSPA@127.0.0.1:3306/test")

三、增,删,改,查

1. 增加

创建表

# 创建表
sql_create_table = """
CREATE TABLE IF NOT EXISTS records_table(
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    age INT NOT NULL
)
"""

db.query(sql_create_table)
#  插入数据,必须使用 事务,不然插入失败,
with db.transaction() as tr:
    # 单条数据操作
    tr.query("insert into records_table(name,age) values('alex',18)")
    tr.query("insert into records_table(name,age) values (:name,:age)", name="alex", age=18)
    records_demo_row = {"name": "username1", "age": 31}
    insert_one_sql = f"insert into records_table(name, age) values ('{records_demo_row['name']}',{records_demo_row['age']})"
    tr.query(insert_one_sql)
    tr.query("insert into records_table(name,age) values (:name,:age)", **records_demo_row)
    # 数据批量操作
    records_demo_rows = [
        {"name": "username2", "age": 32},
        {"name": "username3", "age": 33},
        {"name": "username4", "age": 34},
    ]
    # 批量增加
    tr.bulk_query("insert into records_table(name,age) values (:name,:age)", records_demo_rows)

2. 删除(必须使用事务,不然不生效)

# 删除
with db.transaction() as tr:
    tr.query("delete from records_table where id =:id", id=1)
    tr.bulk_query("delete from records_table where id=:id", [{"id": 1}, {"id": 2}])

3. 修改(必须使用事务,不然不生效)

# 更新 与插入类型
with db.transaction() as tr:
    tr.query("update records_table set age=:age where name=:name", age=100, name="username1")
    tr.bulk_query("update records_table set age=:age where name=:name",
                  [{"name": "username2", "age": 123}, {"name": "username3", "age": 234}])

4.查询

rows = db.query("SELECT name,age FROM records_table WHERE name=:name",name="zhangsan")

# 支持迭代遍历
for row in rows:
 print(row.name, row.get("age"))

# Record 对象
rows[0]
<Record {"name": "zhangsan", "age": 18}>
rows[0].as_dict()
{'id': 1, 'name': 'zhangsan', 'age': 18}
rows[0].name
'zhangsan'
rows[0].get('age')
18

# 获取所有
rows.all()

# 字典
rows.as_dict()

# 查询唯一的一个
rows.one(as_dict=False)

# 获取第一个,字典形式
rows.first(as_dict=True)

# 执行sql文件
rows = db.query_file("a.sql")

参考地址:https://zhangheng18.github.io/2021/04/19/python-records/

posted @ 2024-09-13 15:34  快乐小王子帅气哥哥  阅读(10)  评论(0编辑  收藏  举报

Loading