Akemi

Python使用mysql-connector-python库实现CRUD

2024/11/17

mysql-connector-python是一个官方提供的python库,用于和mysql数据库的交互

功能:数据库连接、执行SQL、处理结果集、事务处理、错误处理

pip3 install mysql-connector-python

mysql环境准备

1
2
3
4
5
6
7
CREATE DATABASE test_db; 
USE test_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT
);

Mysql模块使用方法

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import mysql.connector

# 连接数据库,定义参数
db=mysql.connector.connect(
host='192.168.10.125',
user='root',
password='root',
database='test_db'
)

# 创建游标对象
cursor=db.cursor()

# 插入数据
def insert_data(user,name):
sql = "INSERT INTO users(name,age) VALUES(%s,%s)"
var=(user,name)
cursor.execute(sql,var)
# 提交事务
db.commit()
print(f"insert {cursor.rowcount} records")

# 查询数据
def fetch_users():
cursor.execute("SELECT * FROM users")
result=cursor.fetchall()
for row in result:
print(row)

# 更新数据(改)
def update_user(user_id,name,age):
sql="UPDATE users SET name=%s,age=%s WHERE id=%s"
var=(name,age,user_id)
cursor.execute(sql,var)
db.commit()
print(f"Updated {cursor.rowcount} records")

# 删除数据
def delete_user(user_id):
sql='DELETE FROM users where id=%s'
# var需要是一个元组,加逗号说明是元组
var=(user_id,)
cursor.execute(sql,var)
db.commit()
print(f"Deleted {cursor.rowcount} records")

if __name__ == '__main__':
print("增加两条数据:名称Alice,年龄19;名称Bob,年龄18")
insert_data("Alice",19)
insert_data("Bob",18)

print("查询表数据")
fetch_users()

print("更新数据")
update_user(1,"Alice_2",20)

print("再次查询表数据")
fetch_users()

print("删除两条数据")
delete_user(1)
delete_user(2)

print("关闭连接")
cursor.close()
db.close()

下图update 0条和删除0条都是因为,我新加信息后,自增id已经不是1和2了,所以出现这种情况,问题不大,正常不会去删他

CATALOG
  1. 1. mysql环境准备
  2. 2. Mysql模块使用方法