您当前的位置: 首页 >  Python

彭世瑜

暂无认证

  • 1浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python:cator查询MySQL和SQLite数据库

彭世瑜 发布时间:2021-03-05 17:24:11 ,浏览量:1

现看一个直接使用mysql_connector_python查询数据库的示例


from mysql.connector import Connect

db_config = {
    "database": "data",
    "username": "root",
    "password": "123456",
    "host": "127.0.0.1",
    "port": 3306,
    "charset": "utf8",
    "autocommit": True
}

connect = Connect(**db_config)
cursor = connect.cursor(dictionary=True)

cursor.execute('select * from person where id = %(id)s', {'id': 1})
rows = cursor.fetchall()
print(rows)
# [{'id': 1, 'name': 'Jackk', 'age': 23}]

cursor.close()
connect.close()

使用cator,更为简洁

pip install cator

代码示例

import cator

db_url = "mysql://root:123456@127.0.0.1:3306/data?charset=utf8&autocommit=true"

db = cator.connect(db_url)
rows = db.select('select * from person where id = :id', {'id': 1})
print(rows)
# [{'id': 1, 'name': 'Jackk', 'age': 23}]

db.close()

优势:

  1. 将connection和cursor合二为一;
  2. 增加:key?的占位符支持;
  3. 增加selectinsertupdatedelete等操作返回值预处理,不用再手动使用cursor

文档: https://github.com/mouday/cator

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0913s