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))
相关推荐
GreatSQL2 分钟前
GreatSQL优化技巧:手动实现谓词下推
数据库
小云数据库服务专线8 分钟前
GaussDB 数据库架构师修炼(十八) SQL引擎-计划管理-SPM
数据库·数据库架构·gaussdb
创思通信13 分钟前
4G模块 EC200通过MQTT协议连接到阿里云
数据库·物联网·mqtt·阿里云·at·ec200a
天才测试猿27 分钟前
测试用例如何评审?
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
DDC楼宇自控与IBMS集成系统解读1 小时前
BA 楼宇自控系统 + AI:重构楼宇设备管理的 “智能决策” 体系
大数据·网络·数据库·人工智能·3d·重构
hui函数1 小时前
flask Celery入门:轻松实现异步任务处理
后端·python·flask
JIngJaneIL1 小时前
家庭事务管理系统|基于java和vue的家庭事务管理系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·家庭事务管理系统
暖苏1 小时前
python-多线程(笔记)(持续更新)
大数据·开发语言·python
waynaqua1 小时前
FastAPI开发AI应用教程六:新增用户历史消息
python·openai·fastjson
Jacob02342 小时前
为什么那么多人说大数据只是写SQL?
数据库·后端·sql