现看一个直接使用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()
优势:
- 将connection和cursor合二为一;
- 增加
:key
和?
的占位符支持; - 增加
select
、insert
、update
、delete
等操作返回值预处理,不用再手动使用cursor