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()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
使用cator,更為簡潔
pip install cator
1
代碼示例
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
2
3
4
5
6
7
8
9
10
優勢:
將connection和cursor合二為一;
增加:key 和 ?的占位符支持;
增加select、insert、update、delete等操作返回值預處理,不用再手動使用cursor
文檔: https://github.com/mouday/cator
MySQL Python 數據庫
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。