一、理论
通过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))