数据库连接之records模块

关于python连接mysql数据库,我们已经知道可以用pymysql模块。但是还有一个模块更强大,那就是records模块。下面介绍关于records模块的使用方法。

数据库连接

github链接为:https://github.com/kennethreitz/records
# SQLite 数据库连接串:
sqlite:///:memory: (or, sqlite://)
sqlite:///relative/path/to/file.db
sqlite:////absolute/path/to/file.db
例:db = records.Database(‘sqlite:///users.db’)
# Oracle 数据库连接示例:
先安装 cx_Oracle
oracle://root:1234@ORCL
# MySQL 数据库连接串示例:
mysql://root:12345@localhost/mydb?charset=utf8
# PostgreSQL 数据库连接串示例:
postgresql://postgres:1234@localhost/mydb
# SQL Server 数据库连接示例:
首先安装 pymssql
mssql+pymssql://sa:12345@localhost:1433/mydb
注意:
有些数据库连接方式因第三方模块不同,连接方式可能有多种,上述只是展示其中某一种连接方式,更详细的连接方式请参考 SQLAlchemy。

使用方法

创建表

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)

 

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

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}])

 

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

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}])

  

查询

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")

  

安全参数化:
# Records 支持安全参数化,使用 :variable 定义变量,使用字典传入参数值
params = {'id':1}
rows = db.query('select * from a_user where id = :id',**params)

简洁的数据库事务支持
数据库事务是经常需要使用到的数据库操作,他通常是为了保持数据原子性和一致性。
比如一个转账的数据库操作:
1、从 yuze 账号中读取余额 ,
2、对 yuze 账号余额减去转账 - 400 
3、从 chaoge 账号中把余额读出来 
4、对 chaoge 账号做加法操作(+400)。我们必须保证这 4 步同时执行成功,要么同时都不成功。如果前 2 步已经执行成功,但是到第 3 步发生了错误导致后面都不能执行,
就会出现问题:yuze 的账号被扣了钱,但是 chaoge 的账号却没有加钱。通过数据库事务就能避免这种情况。 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')

  

事务支持

事务支持:
  t = Database.transaction();
  t.commit()
demo:
  db = records.Database()
  tx = db.transaction()
  try:
    db.query(...)
    db.query(...)
    tx.commit()
  except:
    tx.rollback()

  

数据导出

数据导出功能:
Records 还具有完整的 Tablib 集成功能,允许将结果导出到 CSV、XLS、JSON、HTML Tables, YAML、Pandas DataFrames。非常适合与朋友共享数据或生成报告。

1. 以 dataset 方式导出
  dataset = rows.dataset
  print(dataset)

结果:
  id|cid|uname
  --|---|------
  1 |100|tom1
  2 |100|cat1

2. 以 csv 方式导出:结果以逗号分隔
  csv = rows.export('csv')
  print(csv)

结果:
  id,cid,uname
  1,100,tom1
  2,100,cat1

3. 以 yaml 方式导出
  yaml = rows.export('yaml')
  print(yaml)

  结果:
  - cid: 100
    id: 1
    uname: tom1
  - cid: 100
    id: 2
    uname: cat1

4. 以 JSON 方式导出:js对象表示法
  jn = rows.export('json')
  print(jn)

  结果:
  [{"id": 1, "cid": 100, "uname": "tom1"}, {"id": 2, "cid": 100, "uname": "cat1"}]

  demo:
    rows = db.query('SELECT * FROM lemon_user;')
    json_rows = rows.export('yaml')
    print(json_rows)

  # 把数据写入yaml 文件里面
  with open("222.yaml", "w", encoding="utf-8") as f:
      f.write(json_rows)

5. 以 xls/xlsx 方式导出    demo1
    xls = rows.export('xls')
    print(xls)  # b'\xd0\xcf\x11\xe0\xa1\xb1.......'
    demo2
  with open('E://report.xls', 'wb') as f:
      f.write(rows.export('xls'))
  demo3
  rows = db.query('SELECT * FROM lemon_user;')
  with open('users.xlsx', 'wb') as f:
      f.write(rows.export('xlsx'))

6. 以Pandas DataFrame 方式导出
  首先安装好 pandas 模块。
  rows = db.query('select * from a_user')
  df = rows.export('df')
  print(df)

结果:
     id   cid   uname
0     1   100    tom1
1     2   100    cat1
2     3   100  kitty1

 

posted @ 2025-02-08 13:46  羊脂玉净瓶  阅读(14)  评论(0)    收藏  举报