python操作mysql数据库

一、理论

通过python的模块来连接数据库,实现对数据的增删改查。

二、实践

python 复制代码
实验环境
101	mysql
102	python

过程
101
[root@localhost ~]# ls
anaconda-ks.cfg  init.sql  mysql-8.0.36-linux-glibc2.28-x86_64.tar.xz
mysql> source init.sql
Query OK, 1 row affected (0.01 sec)

Database changed
Query OK, 0 rows affected (0.05 sec)

Query OK, 0 rows affected (0.06 sec)

Query OK, 4 rows affected (0.16 sec)
Records: 4  Duplicates: 0  Warnings: 0

Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb             |
+--------------------+
5 rows in set (0.00 sec)


mysql> create user 'root'@'%' identified by 'sooo123';
Query OK, 0 rows affected (0.04 sec)

mysql> grant all on *.* to 'root'@'%';
Query OK, 0 rows affected (0.01 sec)

mysql> alter user 'root'@'%' identified with mysql_native_password by 'sooo123'
    -> ;


102

[root@localhost ~]# dnf -y install mysql
[root@localhost ~]# mysql -uroot -psooo123 -h192.168.10.101
mysql> exit
Bye


[root@localhost ~]# pip install mysql-connector-python  # 安装模块来连接mysql
Looking in indexes: http://mirrors.aliyun.com/pypi/simple
Collecting mysql-connector-python
  Downloading http://mirrors.aliyun.com/pypi/packages/b9/38/96a602ad402fb71175d83bed3178bd8c16e04251d279e314e0bc53e0b861/mysql_connector_python-9.3.0-cp311-cp311-manylinux_2_28_x86_64.whl (33.9 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 33.9/33.9 MB 5.1 MB/s eta 0:00:00
Installing collected packages: mysql-connector-python
Successfully installed mysql-connector-python-9.3.0

[root@localhost ~]# pip install pymysql	# 安装pymysql也可以连接mysql
Looking in indexes: http://mirrors.aliyun.com/pypi/simple
Collecting pymysql
  Downloading http://mirrors.aliyun.com/pypi/packages/0c/94/e4181a1f6286f545507528c78016e00065ea913276888db2262507693ce5/PyMySQL-1.1.1-py3-none-any.whl (44 kB)
Installing collected packages: pymysql
Successfully installed pymysql-1.1.1


[root@localhost ~]# vim q.py 
import pymysql

db=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

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

cursor.execute("select * from users")  # 执行sql语句

results=cursor.fetchall()  # 获取查询结果,fetchall()用于获取所有结果。
for row in results:  # row为变量 results为取值列表,遍历输出。
    print(row)

# 关闭游标连接和数据库连接
cursor.close()
db.close()


[root@localhost ~]# python3 q.py 
(1, 'Alice', 25)
(2, 'Bob', 30)
(3, 'Charlie', 35)
(4, 'David', 28)



[root@localhost ~]# vim q.py 
import pymysql

db=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

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

cursor.execute("insert into users(name,age) values(%s,%s)",("Alice",25)) # %s是占
位符,用后面的数值来替换。

cursor.execute("select * from users")  # 执行sql语句

results=cursor.fetchall()  # 获取查询结果,fetchall()用于获取所有结果。
for row in results:  # row为变量 results为取值列表,遍历输出。
    print(row)

# 关闭游标连接和数据库连接
cursor.close()
db.close()


[root@localhost ~]# python3 q.py 
(1, 'Alice', 25)
(2, 'Bob', 30)
(3, 'Charlie', 35)
(4, 'David', 28)
(5, 'Alice', 25)

[root@localhost ~]# vim q.py
import pymysql

db=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

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

cursor.execute("update users set age=%s where name=%s",(26,"Alice")) # %s是占位符,用后面的数值来替换。
db.commit() # 提交事务,保存更新的数据。

cursor.execute("select * from users")  # 执行sql语句

results=cursor.fetchall()  # 获取查询结果,fetchall()用于获取所有结果。
for row in results:  # row为变量 results为取值列表,遍历输出。
    print(row)

# 关闭游标连接和数据库连接
cursor.close()
db.close()

[root@localhost ~]# python3 q.py 
(1, 'Alice', 26)
(2, 'Bob', 30)
(3, 'Charlie', 35)
(4, 'David', 28)

[root@localhost ~]# vim q.py
import pymysql

db=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

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

cursor.execute("delete from users where name=%s",("Alice",))
db.commit() # 提交事务,保存更新的数据。

cursor.execute("select * from users")  # 执行sql语句

results=cursor.fetchall()  # 获取查询结果,fetchall()用于获取所有结果。
for row in results:  # row为变量 results为取值列表,遍历输出。
    print(row)

# 关闭游标连接和数据库连接
cursor.close()
db.close()

[root@localhost ~]# python3 q.py 
(2, 'Bob', 30)
(3, 'Charlie', 35)
(4, 'David', 28)

[root@localhost ~]# vim q.py
import pymysql

db=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

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

 使用executemany()方法一次执行多条sql语句。
cursor.executemany(
        "insert into users(name,age) values(%s,%s)",
        [("Bob",30),("Charlie",35),("David",28)]
        )
db.commit() # 提交事务,保存更新的数据。

cursor.execute("select * from users")  # 执行sql语句

results=cursor.fetchall()  # 获取查询结果,fetchall()用于获取所有结果。
for row in results:  # row为变量 results为取值列表,遍历输出。
    print(row)

# 关闭游标连接和数据库连接
cursor.close()
db.close()
[root@localhost ~]# python3 q.py 
(2, 'Bob', 30)
(3, 'Charlie', 35)
(4, 'David', 28)
(6, 'Bob', 30)
(7, 'Charlie', 35)
(8, 'David', 28)


[root@localhost ~]# vim q.py 
import pymysql

db=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

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


cursor.execute("select * from users where name like %s",("%a%",))
db.commit() # 提交事务,保存更新的数据。


#cursor.execute("select * from users")  # 执行sql语句

results=cursor.fetchall()  # 获取查询结果,fetchall()用于获取所有结果。
for row in results:  # row为变量 results为取值列表,遍历输出。
    print(row)

# 关闭游标连接和数据库连接
cursor.close()
db.close()

[root@localhost ~]# python3 q.py 
(3, 'Charlie', 35)
(4, 'David', 28)
(7, 'Charlie', 35)
(8, 'David', 28)

[root@localhost ~]# vim q.py 
import pymysql

db=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

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

 内连接查询。
cursor.execute("""
               select users.name,orders.amount
               from users
               inner join orders on users.id=orders.user_id
               """)

results=cursor.fetchall()  # 获取查询结果,fetchall()用于获取所有结果。
for row in results:  # row为变量 results为取值列表,遍历输出。
    print(row)

# 关闭游标连接和数据库连接
cursor.close()
db.close()


[root@localhost ~]# python3 q.py
('Bob', Decimal('150.75'))
('Charlie', Decimal('200.00'))



使用连接池
安装库
[root@localhost ~]# pip3 install dbutils
Successfully installed dbutils-3.1.0


[root@localhost ~]# vim b.py
from dbutils.pooled_db import PooledDB
import pymysql

# 数据库连接配置
dbconfig={
        "host":"192.168.10.101",
        "user":"root",
        "password":"sooo123",
        "database":"testdb"
        }
# 创建连接池
connection_pool=PooledDB(
        creator=pymysql,  # 使用pymysql作为数据库连接库。
        maxconnections=5, # 连接池中最大连接数。
        **dbconfig    # dbconfig是前面定义的字典,**表示引用字典,将字典中的键值对解包为独立的关键字参数。
        )

# 从连接池中获取连接时,可用connection()方法。每次获取到的连接都可以直接执行数据>库操作。
db_connection=connection_pool.connection()
cursor=db_connection.cursor()

cursor.execute("select * from users")
results=cursor.fetchall()

for row in results:
    print(row)
    

cursor.close()

db_connection.close()  # 关闭连接池,连接会自动归还给连接池

[root@localhost ~]# python3 b.py
(2, 'Bob', 30)
(3, 'Charlie', 35)
(4, 'David', 28)
(6, 'Bob', 30)
(7, 'Charlie', 35)
(8, 'David', 28)

[root@localhost ~]# vim c.py


事务
[root@localhost ~]# vim c.py
import pymysql

# 连接到数据库
conn=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

cursor=conn.cursor()

conn.autocommit=False

try:
    # 开始事务
    cursor.execute("start transaction")

    # 执行插入操作
    cursor.execute("insert into users(name,age) values('Eve',22)")
    cursor.execute("insert into orders (user_id,amount) values((select id from users where name='Eve'),120.50)")

    # 提交事务
    conn.commit()
    print("事务已提交.")

except pymysql.MySQLError as err:
    # 如果发生错误,回滚事务
    print (f"错误:{err}")
    conn.rollback()
    print ("事务已回滚。")

finally:
           # 关闭游标和连接
           cursor.close()



[root@localhost ~]# python3 c.py
事务已提交.


[root@localhost ~]# vim d.py
import pymysql

# 连接到数据库
conn=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

cursor=conn.cursor()

cursor.execute("select * from users")
#cursor.execue("select * from orders")

aaa=cursor.fetchall()
for row in aaa:
    print(row)


cursor.close()
conn.close()

[root@localhost ~]# python3 d.py
(2, 'Bob', 30)
(3, 'Charlie', 35)
(4, 'David', 28)
(6, 'Bob', 30)
(7, 'Charlie', 35)
(8, 'David', 28)
(9, 'Eve', 22)


[root@localhost ~]# vim d.py
import pymysql

# 连接到数据库
conn=pymysql.connect(
        host="192.168.10.101",
        user="root",
        password="sooo123",
        database="testdb"
        )

cursor=conn.cursor()

#cursor.execute("select * from users")
cursor.execute("select * from orders")

aaa=cursor.fetchall()
for row in aaa:
    print(row)


cursor.close()
conn.close()

[root@localhost ~]# python3 c.py
(2, 2, Decimal('150.75'), datetime.datetime(2025, 4, 21, 9, 25, 54))
(3, 3, Decimal('200.00'), datetime.datetime(2025, 4, 21, 9, 25, 54))
(5, 9, Decimal('120.50'), datetime.datetime(2025, 5, 25, 20, 35, 36))
相关推荐
程序员龙叔12 小时前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户83562907805115 小时前
使用 Python 操作 Word 内容控件
后端·python
摇滚侠15 小时前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
码云骑士17 小时前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python
麦聪聊数据17 小时前
数据服务化时代:企业数据能力输出的核心路径
数据库
ApacheSeaTunnel17 小时前
实战演示 | 基于 Apache SeaTunnel 与 Apache DolphinScheduler 实现 MySQL 到 Doris 离线定时增量同步
大数据·mysql·开源·doris·数据集成·seatunnel·数据同步
shushangyun_17 小时前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
闵孚龙17 小时前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
DARLING Zero two♡17 小时前
【MySQL数据库】数据类型与表约束
数据库·mysql