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))
相关推荐
猎嘤一号22 分钟前
Windows11桌面解锁守护脚本
开发语言·python·opencv
蓝婷儿1 小时前
Python 数据建模与分析项目实战预备 Day 2 - 数据构建与字段解析(模拟简历结构化数据)
开发语言·python·机器学习
李白洗一夜1 小时前
(新手友好)MySQL学习笔记(12):触发器,视图,三范式
笔记·学习·mysql
青衫客361 小时前
浅谈 Python 中的 yield——yield的返回值与send()的关系
开发语言·python
ladymorgana2 小时前
【数据库】PostgreSQL 与 MySQL 全方位对比
数据库·mysql·postgresql
测试老哥2 小时前
Python+Selenium实现自动化测试
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
张璐月2 小时前
mysql 散记:innodb引擎和memory引擎对比 sql语句少用函数 事务与长事务
数据库·sql·mysql
noravinsc3 小时前
django queryset 去重
数据库·django·sqlite
望获linux4 小时前
【实时Linux实战系列】硬实时与软实时设计模式
linux·运维·服务器·数据库·操作系统·rtos·嵌入式软件
Dxy12393102166 小时前
Python PDFplumber详解:从入门到精通的PDF处理指南
开发语言·python·pdf