Cập nhật dữ liệu trong bảng

Nhập môn Cơ sở dữ liệu với Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Cập nhật dữ liệu trong bảng

  • Thực hiện với câu lệnh update()
  • Tương tự insert() nhưng có mệnh đề where để xác định bản ghi sẽ cập nhật
  • Thêm các giá trị cần cập nhật bằng values() dưới dạng cặp column=value
Nhập môn Cơ sở dữ liệu với Python

Cập nhật một hàng

from sqlalchemy import update

stmt = update(employees) stmt = stmt.where(employees.columns.id == 3) stmt = stmt.values(active=True)
result_proxy = connection.execute(stmt) print(result_proxy.rowcount)
1
Nhập môn Cơ sở dữ liệu với Python

Cập nhật nhiều hàng

  • Tạo mệnh đề where chọn tất cả bản ghi cần cập nhật
Nhập môn Cơ sở dữ liệu với Python

Chèn nhiều hàng

stmt = update(employees)
stmt = stmt.where(employees.columns.active == True)

stmt = stmt.values(active=False, salary=0.00)
result_proxy = connection.execute(stmt) print(result_proxy.rowcount)
3
Nhập môn Cơ sở dữ liệu với Python

Cập nhật tương quan

new_salary = select([employees.columns.salary])
new_salary = new_salary.order_by(
    desc(employees.columns.salary))
new_salary = new_salary.limit(1)

stmt = update(employees)
stmt = stmt.values(salary=new_salary)
result_proxy = connection.execute(stmt)
print(result_proxy.rowcount)
3
Nhập môn Cơ sở dữ liệu với Python

Cập nhật tương quan

  • Dùng câu lệnh select() để lấy giá trị cho cột cần cập nhật
  • Thường dùng để đặt giá trị tối đa hoặc đổi chuỗi theo viết tắt từ bảng khác
Nhập môn Cơ sở dữ liệu với Python

Passons à la pratique !

Nhập môn Cơ sở dữ liệu với Python

Preparing Video For Download...