Pythoncator查询MySQL和SQLite数据库

网友投稿 504 2022-05-30

现看一个直接使用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

Python:cator查询MySQL和SQLite数据库

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小时内删除侵权内容。

上一篇:AR502H 二次开发日记
下一篇:使用Pandas的read_html方法读取网页Table表格数据
相关文章