天天看點

Python:cator查詢MySQL和SQLite資料庫

現看一個直接使用

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:[email protected]: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. select

    insert

    update

    delete

    等操作傳回值預處理,不用再手動使用cursor

文檔:

https://github.com/mouday/cator