翼度科技»论坛 编程开发 python 查看内容

day26-python操作MySQL和实战

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
1. 事务

innodb引擎中支持事务,myisam不支持。
  1. CREATE TABLE `users` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  3.   `name` varchar(32) DEFAULT NULL,
  4.   `amount` int(11) DEFAULT NULL
  5. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码

例如:李杰 给 武沛齐 转账 100,那就会涉及2个步骤。

  • 李杰账户 减100
  • 武沛齐账户 加 100
这两个步骤必须同时完成才算完成,并且如果第一个完成、第二步失败,还是回滚到初始状态。
事务,就是来解决这种情况的。  大白话:要成功都成功;要失败都失败。
事务的具有四大特性(ACID):

  • 原子性(Atomicity)
    1. 原子性是指事务包含的所有操作不可分割,要么全部成功,要么全部失败回滚。
    复制代码
  • 一致性(Consistency)
    1. 执行的前后数据的完整性保持一致。
    复制代码
  • 隔离性(Isolation)
    1. 一个事务执行的过程中,不应该受到其他事务的干扰。
    复制代码
  • 持久性(Durability)
    1. 事务一旦结束,数据就持久到数据库
    复制代码
1.1 MySQL客户端
  1. mysql> select * from users;
  2. +----+---------+---------+
  3. | id | name    | amount  |
  4. +----+---------+---------+
  5. |  1 | wupeiqi |    5    |
  6. |  2 |  alex   |    6    |
  7. +----+---------+---------+
  8. 3 rows in set (0.00 sec)
  9. mysql> begin;  -- 开启事务 start transaction;
  10. Query OK, 0 rows affected (0.00 sec)
  11. mysql> update users set amount=amount-2 where id=1;   -- 执行操作
  12. Query OK, 1 row affected (0.00 sec)
  13. Rows matched: 1  Changed: 1  Warnings: 0
  14. mysql> update users set amount=amount+2 where id=2;   -- 执行操作
  15. Query OK, 1 row affected (0.00 sec)
  16. Rows matched: 1  Changed: 1  Warnings: 0
  17. mysql> commit;  -- 提交事务  rollback;
  18. Query OK, 0 rows affected (0.00 sec)
  19. mysql> select * from users;
  20. +----+---------+---------+
  21. | id | name    | amount  |
  22. +----+---------+---------+
  23. |  1 | wupeiqi |    3    |
  24. |  2 |  ale x  |    8    |
  25. +----+---------+---------+
  26. 3 rows in set (0.00 sec)
复制代码
  1. mysql> select * from users;
  2. +----+---------+---------+
  3. | id | name    | amount  |
  4. +----+---------+---------+
  5. |  1 | wupeiqi |    3    |
  6. |  2 |  ale x  |    8    |
  7. +----+---------+---------+
  8. 3 rows in set (0.00 sec)
  9. mysql> begin; -- 开启事务
  10. Query OK, 0 rows affected (0.00 sec)
  11. mysql> update users set amount=amount-2 where id=1; -- 执行操作(此时数据库中的值已修改)
  12. Query OK, 1 row affected (0.00 sec)
  13. Rows matched: 1  Changed: 1  Warnings: 0
  14. mysql> rollback; -- 事务回滚(回到原来的状态)
  15. Query OK, 0 rows affected (0.00 sec)
  16. mysql> select * from users;
  17. +----+---------+---------+
  18. | id | name    | amount  |
  19. +----+---------+---------+
  20. |  1 | wupeiqi |    3    |
  21. |  2 |  ale x  |    8    |
  22. +----+---------+---------+
  23. 3 rows in set (0.00 sec)
复制代码
1.2 Python代码
  1. import pymysql
  2. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db='userdb')
  3. cursor = conn.cursor()
  4. # 开启事务
  5. conn.begin()
  6. try:
  7.     cursor.execute("update users set amount=1 where id=1")
  8.     int('asdf')
  9.     cursor.execute("update tran set amount=2 where id=2")
  10. except Exception as e:
  11.     # 回滚
  12.     print("回滚")
  13.     conn.rollback()
  14. else:
  15.     # 提交
  16.     print("提交")
  17.     conn.commit()
  18. cursor.close()
  19. conn.close()
复制代码
2. 锁

在用MySQL时,不知你是否会疑问:同时有很多做更新、插入、删除动作,MySQL如何保证数据不出错呢?
MySQL中自带了锁的功能,可以帮助我们实现开发过程中遇到的同时处理数据的情况。对于数据库中的锁,从锁的范围来讲有:

  • 表级锁,即A操作表时,其他人对整个表都不能操作,等待A操作完之后,才能继续。
  • 行级锁,即A操作表时,其他人对指定的行数据不能操作,其他行可以操作,等待A操作完之后,才能继续。
  1. MYISAM支持表锁,不支持行锁;
  2. InnoDB引擎支持行锁和表锁。
  3. 即:在MYISAM下如果要加锁,无论怎么加都会是表锁。
  4.     在InnoDB引擎支持下如果是基于索引查询的数据则是行级锁,否则就是表锁。
复制代码
所以,一般情况下我们会选择使用innodb引擎,并且在 搜索 时也会使用索引(命中索引)。
接下来的操作就基于innodb引擎来操作:
  1. CREATE TABLE `L1` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `name` varchar(255) DEFAULT NULL,
  4.   `count` int(11) DEFAULT NULL,
  5.   PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
复制代码

在innodb引擎中,update、insert、delete的行为内部都会先申请锁(排它锁),申请到之后才执行相关操作,最后再释放锁。
  1. 所以,当多个人同时像数据库执行:insert、update、delete等操作时,内部加锁后会排队逐一执行。
复制代码
而select则默认不会申请锁。
  1. select * from xxx;
复制代码
如果,你想要让select去申请锁,则需要配合 事务 + 特殊语法来实现。

  • for update,排它锁,加锁之后,其他不可以读写。
    1. begin;
    2.         select * from L1 where name="武沛齐" for update;    -- name列不是索引(表锁)
    3. commit;
    复制代码
    1. begin; -- 或者 start transaction;
    2.         select * from L1 where id=1 for update;                          -- id列是索引(行锁)
    3. commit;
    复制代码
  • lock in share mode ,共享锁,加锁之后,其他可读但不可写。
    1. begin;
    2.         select * from L1 where name="武沛齐" lock in share mode;    -- 假设name列不是索引(表锁)
    3. commit;
    复制代码
    1. begin; -- 或者 start transaction;
    2.         select * from L1 where id=1 lock in share mode;           -- id列是索引(行锁)
    3. commit;
    复制代码
2.1 排它锁

排它锁( for update),加锁之后,其他事务不可以读写。
应用场景:总共100件商品,每次购买一件需要让商品个数减1 。
  1. A: 访问页面查看商品剩余 100
  2. B: 访问页面查看商品剩余 100
  3. 此时 A、B 同时下单,那么他们同时执行SQL:
  4.         update goods set count=count-1 where id=3
  5. 由于Innodb引擎内部会加锁,所以他们两个即使同一时刻执行,内部也会排序逐步执行。
  6. 但是,当商品剩余 1个时,就需要注意了。
  7. A: 访问页面查看商品剩余 1
  8. B: 访问页面查看商品剩余 1
  9. 此时 A、B 同时下单,那么他们同时执行SQL:
  10.         update goods set count=count-1 where id=3
  11. 这样剩余数量就会出现 -1,很显然这是不正确的,所以应该怎么办呢?
  12. 这种情况下,可以利用 排它锁,在更新之前先查询剩余数量,只有数量 >0 才可以购买,所以,下单时应该执行:
  13.         begin; -- start transaction;
  14.         select count from goods where id=3 for update;
  15.         -- 获取个数进行判断
  16.         if 个数>0:
  17.                 update goods set count=count-1 where id=3;
  18.         else:
  19.                 -- 已售罄
  20.         commit;
复制代码
基于Python代码示例:
  1. import pymysql
  2. import threading
  3. def task():
  4.     conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db='userdb')
  5.     cursor = conn.cursor(pymysql.cursors.DictCursor)
  6.     # cursor = conn.cursor()
  7.        
  8.     # 开启事务
  9.     conn.begin()
  10.     cursor.execute("select id,age from tran where id=2 for update")
  11.     # fetchall      ( {"id":1,"age":10},{"id":2,"age":10}, )   ((1,10),(2,10))
  12.     # {"id":1,"age":10}   (1,10)
  13.     result = cursor.fetchone()
  14.     current_age = result['age']
  15.    
  16.     if current_age > 0:
  17.         cursor.execute("update tran set age=age-1 where id=2")
  18.     else:
  19.         print("已售罄")
  20.     conn.commit()
  21.     cursor.close()
  22.     conn.close()
  23. def run():
  24.     for i in range(5):
  25.         t = threading.Thread(target=task)
  26.         t.start()
  27. if __name__ == '__main__':
  28.     run()
复制代码
2.2 共享锁

共享锁( lock in share mode),可以读,但不允许写。
加锁之后,后续其他事物可以可以进行读,但不允许写(update、delete、insert),因为写的默认也会加锁。
Locking Read Examples
Suppose that you want to insert a new row into a table child, and make sure that the child row has a parent row in table parent. Your application code can ensure referential integrity throughout this sequence of operations.
First, use a consistent read to query the table PARENT and verify that the parent row exists. Can you safely insert the child row to table CHILD? No, because some other session could delete the parent row in the moment between your SELECT and your INSERT, without you being aware of it.
To avoid this potential issue, perform the SELECT using LOCK IN SHARE MODE:
  1. SELECT * FROM parent WHERE NAME = 'Jones' LOCK IN SHARE MODE;
复制代码
After the LOCK IN SHARE MODE query returns the parent 'Jones', you can safely add the child record to the CHILD table and commit the transaction. Any transaction that tries to acquire an exclusive lock in the applicable row in the PARENT table waits until you are finished, that is, until the data in all tables is in a consistent state.
3. 数据库连接池


在操作数据库时需要使用数据库连接池。
  1. pip3.9 install pymysql
  2. pip3.9 install dbutils
复制代码
  1. import threading
  2. import pymysql
  3. from dbutils.pooled_db import PooledDB
  4. MYSQL_DB_POOL = PooledDB(
  5.     creator=pymysql,  # 使用链接数据库的模块
  6.     maxconnections=5,  # 连接池允许的最大连接数,0和None表示不限制连接数
  7.     mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
  8.     maxcached=3,  # 链接池中最多闲置的链接,0和None不限制
  9.     blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
  10.     setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
  11.     ping=0,
  12.     # ping MySQL服务端,检查是否服务可用。
  13.     # 如:0 = None = never, 1 = default = whenever it is requested,
  14.     # 2 = when a cursor is created, 4 = when a query is executed, 7 = always
  15.     host='127.0.0.1',
  16.     port=3306,
  17.     user='root',
  18.     password='root123',
  19.     database='userdb',
  20.     charset='utf8'
  21. )
  22. def task():
  23.     # 去连接池获取一个连接
  24.     conn = MYSQL_DB_POOL.connection()
  25.     cursor = conn.cursor(pymysql.cursors.DictCursor)
  26.    
  27.     cursor.execute('select sleep(2)')
  28.     result = cursor.fetchall()
  29.     print(result)
  30.     cursor.close()
  31.     # 将连接交换给连接池
  32.     conn.close()
  33. def run():
  34.     for i in range(10):
  35.         t = threading.Thread(target=task)
  36.         t.start()
  37. if __name__ == '__main__':
  38.     run()
复制代码
4. SQL工具类

基于数据库连接池开发一个公共的SQL操作类,方便以后操作数据库。
4.1 单例和方法
  1. # db.py
  2. import pymysql
  3. from dbutils.pooled_db import PooledDB
  4. class DBHelper(object):
  5.     def __init__(self):
  6.         # TODO 此处配置,可以去配置文件中读取。
  7.         self.pool = PooledDB(
  8.             creator=pymysql,  # 使用链接数据库的模块
  9.             maxconnections=5,  # 连接池允许的最大连接数,0和None表示不限制连接数
  10.             mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
  11.             maxcached=3,  # 链接池中最多闲置的链接,0和None不限制
  12.             blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
  13.             setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
  14.             ping=0,
  15.             # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
  16.             host='127.0.0.1',
  17.             port=3306,
  18.             user='root',
  19.             password='root123',
  20.             database='userdb',
  21.             charset='utf8'
  22.         )
  23.     def get_conn_cursor(self):
  24.         conn = self.pool.connection()
  25.         cursor = conn.cursor(pymysql.cursors.DictCursor)
  26.         return conn, cursor
  27.     def close_conn_cursor(self, *args):
  28.         for item in args:
  29.             item.close()
  30.     def exec(self, sql, **kwargs):
  31.         conn, cursor = self.get_conn_cursor()
  32.         cursor.execute(sql, kwargs)
  33.         conn.commit()
  34.         self.close_conn_cursor(conn, cursor)
  35.     def fetch_one(self, sql, **kwargs):
  36.         conn, cursor = self.get_conn_cursor()
  37.         cursor.execute(sql, kwargs)
  38.         result = cursor.fetchone()
  39.         self.close_conn_cursor(conn, cursor)
  40.         return result
  41.     def fetch_all(self, sql, **kwargs):
  42.         conn, cursor = self.get_conn_cursor()
  43.         cursor.execute(sql, kwargs)
  44.         result = cursor.fetchall()
  45.         self.close_conn_cursor(conn, cursor)
  46.         return result
  47. db = DBHelper()
复制代码
  1. from db import db
  2. db.exec("insert into d1(name) values(%(name)s)", name="武沛齐666")
  3. ret = db.fetch_one("select * from d1")
  4. print(ret)
  5. ret = db.fetch_one("select * from d1 where id=%(nid)s", nid=3)
  6. print(ret)
  7. ret = db.fetch_all("select * from d1")
  8. print(ret)
  9. ret = db.fetch_all("select * from d1 where id>%(nid)s", nid=2)
  10. print(ret)
复制代码
4.2 上下文管理

如果你想要让他也支持 with 上下文管理。
  1. with 获取连接:
  2.         执行SQL(执行完毕后,自动将连接交还给连接池)
复制代码
  1. # db_context.py
  2. import threading
  3. import pymysql
  4. from dbutils.pooled_db import PooledDB
  5. POOL = PooledDB(
  6.     creator=pymysql,  # 使用链接数据库的模块
  7.     maxconnections=5,  # 连接池允许的最大连接数,0和None表示不限制连接数
  8.     mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
  9.     maxcached=3,  # 链接池中最多闲置的链接,0和None不限制
  10.     blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
  11.     setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
  12.     ping=0,
  13.     host='127.0.0.1',
  14.     port=3306,
  15.     user='root',
  16.     password='root123',
  17.     database='userdb',
  18.     charset='utf8'
  19. )
  20. class Connect(object):
  21.     def __init__(self):
  22.         self.conn = conn = POOL.connection()
  23.         self.cursor = conn.cursor(pymysql.cursors.DictCursor)
  24.     def __enter__(self):
  25.         return self
  26.     def __exit__(self, exc_type, exc_val, exc_tb):
  27.         self.cursor.close()
  28.         self.conn.close()
  29.     def exec(self, sql, **kwargs):
  30.         self.cursor.execute(sql, kwargs)
  31.         self.conn.commit()
  32.     def fetch_one(self, sql, **kwargs):
  33.         self.cursor.execute(sql, kwargs)
  34.         result = self.cursor.fetchone()
  35.         return result
  36.     def fetch_all(self, sql, **kwargs):
  37.         self.cursor.execute(sql, kwargs)
  38.         result = self.cursor.fetchall()
  39.         return result
复制代码
  1. from db_context import Connect
  2. with Connect() as obj:
  3.     # print(obj.conn)
  4.     # print(obj.cursor)
  5.     ret = obj.fetch_one("select * from d1")
  6.     print(ret)
  7.     ret = obj.fetch_one("select * from d1 where id=%(id)s", id=3)
  8.     print(ret)
复制代码
5.其他

navicat,是一个桌面应用,让我们可以更加方便的管理MySQL数据库。
总结

本节内容比较重要,也是开发中经常会使用到的技能。

  • 事务,解决批量操作同时成功或失败的问题。
  • 锁,解决并发处理的问题。
  • 数据库连接池,解决多个人请求连接数据库的问题。
  • SQL工具类,解决连接数据库代码重复的问题。
  • navicat工具
大作业:开发博客系统

请基于你掌握的所有技能,实现 day24  博客系统的所有功能。
根据如下的业务需求设计相应的表结构,内部需涵盖如下功能。

  • 注册
  • 登录
  • 发布博客
  • 查看博客列表,显示博客标题、创建时间、阅读数量、评论数量、赞数量等。(支持分页查看)
  • 博客详细,显示博文详细、评论 等。

    • 发表评论
    • 赞 or 踩
    • 阅读数量 + 1

可参考如下图片来设计相应的表结构。
1. 注册和登录


2. 文章列表


3. 文章详细


4. 评论 & 阅读 & 赞 & 踩


注意:假设都是一级评论(不能回复评论)。
参考代码:https://files.cnblogs.com/files/blogs/814578/blog.zip?t=1714289879&download=true

来源:https://www.cnblogs.com/sbhglqy/p/18163862
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具