Python服务器运维笔记:第一章数据库精讲 - 1.1.6 update与delete语句

前言:本文是学习网易微专业的《python全栈工程师》 中的《服务器运维开发工程师》专题的课程笔记,欢迎学习交流。同时感谢老师们的精彩传授!

一、课程目标

  • delete语句结构
  • update语句
  • update

二、详情解读

2.1.delete语句

delete用于从数据表中删除数据记录,将符合condition的记录从数据表中删除。
注意:如果不带条件删除,相当于删库。在mysql中默认不允许不带条件的删除。

delete from table where condition

例子:

delete from users limit 10 # 删除10条会员记录
delete from users where id > 10 and id < 15 # 删除 id 在10~15之间的会员记录
2.2.udpate语句

update语句用于更新数据表的记录

update table set field1=new_val1, field2=new_val2 where condition

例子:将 id = 15的会员年龄改为20, 性别改为男

update users set age=20, sex="男" where id = 15

mysql中使用update语句,新建文件07_delete_mysql_connector.py

# -*- coding=utf-8 -*-
import mysql.connector as connector

cnx = connector.connect(user='root', password='root', host='localhost', database='mycms')

cursor = cnx.cursor()

sql = "delete from users where user_id=11102"
cursor.execute(sql)
cnx.commit() # 记得加上这一行
res = cursor.rowcount
print(res)

cursor.close()
cnx.close()

执行结果:
在这里插入图片描述
sqlalchemy中使用delete语句,新建08_delete_sqlalchemy.py

# -*- coding=utf-8 -*-

from select_sqlalchemy import session, Users
from sqlalchemy import or_

# obj = session.query(Users).filter_by(user_id=3).one()
# print(obj.username)
# and
# objs = session.query(Users).filter(Users.user_id>20 , Users.user_id<30).all()
# or
# objs = session.query(Users).filter(or_(Users.user_id==100, Users.user_id==10)).all()

def getUsers():
    objs = session.query(Users).filter(Users.user_id > 20,
                                       Users.user_id < 30).all()
    return objs

for obj in getUsers():
    print(obj.username)

# 删除
session.delete(getUsers()[0])
session.commit()


# 检查是否删除
print("*"*100)
for obj in getUsers():
    print(obj.username)

其中同级目录的select_sqlalchemy.py文件内容如下:

# -*- coding=utf-8 -*-
# 需要安装sqlalchemy
# pip install sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install pymysql
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, Enum
from sqlalchemy.ext.declarative import declarative_base

# 创建数据库引擎
engine = create_engine("mysql+pymysql://root:123456@localhost/mycms")

# 创建会话对象,根据不同的数据库引擎创建对应的会话对象
Session = sessionmaker(bind=engine)
# 创建会话对象实例
session= Session()

# Base为映射基类
Base = declarative_base()
# 数据表模型
class Users(Base):
    __tablename__ = "users"
    user_id =  Column(Integer, primary_key=True)
    username = Column(String(25))
    realname = Column(String(25))
    password = Column(String(64))
    age = Column(Integer)


# 查询
if __name__ == "__main__":
    res = session.query(Users, Users.username).filter(Users.username.like("%x%")).limit(10).all()

    print(res)

mysql中使用update语句,新建09_update_mysql.py

# -*- coding=utf-8 -*-
import mysql.connector as connector

cnx = connector.connect(user='root', password='root', host='localhost', database='mycms')

cursor = cnx.cursor()

def getUser(user_id):
    sql = "select * from users where user_id=4"
    cursor.execute(sql)
    res = cursor.fetchone()
    print(res)
getUser(4)

# sql1 = "insert into users set user_id 4, username='luxp'"
sql2 = "update users set age=12 where user_id=4"
try:
    cursor.execute(sql2)
    cnx.commit()
except Exception as e:
    print(e)
    cnx.rollback()

sqlalchemy中使用update语句,新建10_update_sqlalchemy.py

# -*- coding=utf-8 -*-

from select_sqlalchemy import session, Users
from sqlalchemy import or_

obj = session.query(Users).filter_by(user_id=4).one()
# print(obj.username)
# and
# objs = session.query(Users).filter(Users.user_id>3 , Users.user_id<10).all()
# or
# objs = session.query(Users).filter(or_(Users.user_id==100,
#                                Users.user_id==10)).all())
print(dir(obj))

print(obj.username, obj.age)

# 更改
obj.age = 100
session.commit()

# 查看更改结果
obj = session.query(Users).filter_by(user_id=4).one()

print(obj.username, obj.age)
2.3.锁的概念
2.3.1.无形中的一把锁
奖品_id 奖品名 中奖者
(winner)
中奖日期
1 一等奖

中奖逻辑:
谁先把中奖者列修改为自己的名字,就是谁中奖。

这样就会给服务器同时提交两条update语句:
张三:

update prize set winner="zhangsan" where p_id=1;

李四:

update prize set winner="lisi" where p_id=1;

如果这样修改的话,毫无疑问,不是最快的人抢到,而是最慢的人抢到。
李四只能等,等到张三解锁的时候,中奖者项已经不是null值了。

张三给下面这条记录上锁了:

奖品_id 奖品名 中奖者 中奖日期
1 一等奖

使用:

update prize set winner = "zhangsan" where p_id=1 and winner is null

update的时候,会给这一行加锁(innodb引擎)。锁的机制相对比较复杂,通常条件下,mysql会自动加锁,在对锁理解不够清晰的情况下,不要手动加锁。

实操:
新建文件11_update_lock.py,写入下面代码:

# -*- coding=utf-8 -*-
import mysql.connector  as connector
from threading import Thread

def updateAge(age):
    sql = "update users set age={age} where user_id=3 and age is NULL ;"
    sql = sql.format(age=age)
    cnx = connector.connect(user='root', password='123456',
                            host='localhost', database='mycms')
    cursor = cnx.cursor()
    try:
        cursor.execute(sql)
        cnx.commit()
        print("age="+str(age)+"影响条数:"+str(cursor.rowcount))
    except Exception as e:
        print(e)
        cnx.rollback()
    cursor.close()
    cnx.close()

#  模拟多人并发
for i in range(1,10):
    t = Thread(target=updateAge, args=(i,))
    t.start()

三、课程小结

  • 01 delete语句
  • 02 update语句
  • 03 锁

本节课主要学习了delete语句和update语句,这两个语句结构简单,但是在使用时需要一个意识:即锁的概念
更新数据时,可能会有多个线程在同时修改,它们之间的执行需要一个顺序,这个顺序就是根据来决定的。首先上锁的线程可以先修改这条数据,修改完成之后,就打开锁,然后其他的线程才能加锁修改数据。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章