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))
相关推荐
nVisual几秒前
机柜PDU安装位置与空间建模方案
大数据·网络·数据库·信息可视化·数据中心基础设施管理
weixin_668几秒前
Cursor-superpowers插件用法
数据库·人工智能
小小代码狗6 分钟前
SQLi-Labs 基础注入实战教程(Less-1 ~ Less-5and Less-9)
服务器·python·php
NWU_白杨7 分钟前
三种常用的数据存储技术
数据库·redis·mysql·sqlite
蓝创工坊Blue Foundry29 分钟前
图片文字提取到 Excel:批量任务如何先定义要交付的字段
运维·服务器·开发语言·数据库·自动化·ocr·excel
nanawinona43 分钟前
2026年下半年量化学习,不同基础要查不同缺口
人工智能·python
一嘴一个橘子1 小时前
MySqL 的 B+树、 叶子节点、非叶子节点
mysql
麦聪聊数据1 小时前
企业数据市场建设(三):API 化服务封装,让数据开箱即用、避免重复开发
数据库
脱胎换骨-军哥1 小时前
C++数据库存储引擎内核开发:B+树索引与MVCC并发控制的完整实现
数据库·c++·b树
CTA量化套保1 小时前
最新量化表达入门,从概念规则到简单实现
人工智能·python