Python:mysql-connector-python模块对MySQL数据库进行增删改查

网友投稿 731 2022-05-30

Mysql文档:https://dev.mysql.com/doc/connector-python/en/

PYPI: https://pypi.org/project/mysql-connector-python/

mysql-connector-python 是MySQL官方的Python语言MySQL连接模块

安装

$ pip install mysql-connector-python

1

代码示例

连接管理

# -*- coding: utf-8 -*- import mysql.connector db_config = { "database": "mydata", "user": "root", "password": "123456", "host": "127.0.0.1", "port": 3306, } # 连接数据库获取游标,可以设置返回数据的格式,元组,命令元组,字典等... connect = mysql.connector.Connect(**db_config) cursor = connect.cursor(dictionary=True) # 关闭游标和连接 cursor.close() connect.close()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

写操作

数据 写入 和 更新 都可以使用 execute 和 executemany

删除就使用execute

写操作都需要 commit 才会生效

# 插入元组数据 insert_tuple_sql = "insert into student(name, age) values(%s, %s)" data = ("Tom", 23) cursor.execute(insert_tuple_sql, data) connect.commit() print(cursor.lastrowid) # 一般插入一条时使用,获取插入id # 插入多条元组数据 insert_tuple_sql = "insert into student(name, age) values(%s, %s)" data = [ ("Tom", 23), ("Jack", 25), ] cursor.executemany(insert_tuple_sql, data) connect.commit() # 插入字典数据 insert_dict_sql = "insert into student(name, age) values(%(name)s, %(age)s)" data = { "name": "Tom", "age": 25 } cursor.execute(insert_dict_sql, data) connect.commit() # 插入多条字典数据 insert_dict_sql = "insert into student(name, age) values(%(name)s, %(age)s)" data = [ { "name": "Tom", "age": 26 }, { "name": "Jack", "age": 27 } ] cursor.executemany(insert_dict_sql, data) connect.commit()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

读操作

cursor.execute("select * from student where name=%s limit 3", ("Tom",)) rows = cursor.fetchall() print(rows) # 因为开始设置的返回数据格式是字典 dictionary ,所以直接返回字典数据 # [ # {'id': 1, 'name': 'Tom', 'age': 23}, # {'id': 2, 'name': 'Tom', 'age': 23}, # {'id': 3, 'name': 'Tom', 'age': 25} #] # 获取一些元数据信息 print(cursor.column_names) # ('id', 'name', 'age') print(cursor.description) # [ # ('id', 3, None, None, None, None, 0, 16899), # ('name', 253, None, None, None, None, 1, 0), # ('age', 3, None, None, None, None, 1, 0) #] print(cursor.rowcount) # 3 print(cursor.statement) # select * from student where name='Tom' limit 3 print(cursor.with_rows) # True

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Python:mysql-connector-python模块对MySQL数据库进行增删改查

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

MySQL Python 数据库

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Elasticsearch添加拼音搜索支持
下一篇:【智简网络】如何使用SDK工具的调用NCE-Campus北向API接口
相关文章