前言:本文是學習網易微專業的《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
語句,這兩個語句結構簡單,但是在使用時需要一個意識:即鎖的概念。
更新數據時,可能會有多個線程在同時修改,它們之間的執行需要一個順序,這個順序就是根據鎖來決定的。首先上鎖的線程可以先修改這條數據,修改完成之後,就打開鎖,然後其他的線程才能加鎖修改數據。