Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เมธอด commit() ใน Python MySQL คืออะไร


เมธอด commit() ใช้ยืนยันการเปลี่ยนแปลงที่ผู้ใช้ทำไปที่ฐานข้อมูล ทุกครั้งที่มีการเปลี่ยนแปลงข้อมูลด้วย UPDATE หรือคำสั่งอื่น ต้องใช้ commit() มิฉะนั้นการเปลี่ยนแปลงจะไม่สะท้อนในฐานข้อมูล

ไวยากรณ์

db.commit()

db คือออบเจ็กต์การเชื่อมต่อฐานข้อมูล

ขั้นตอนอัปเดตข้อมูลและ commit การเปลี่ยนแปลงในตารางด้วย MySQL ใน Python

  • นำเข้า MySQL Connector

  • สร้างการเชื่อมต่อด้วย connect()

  • สร้างออบเจ็กต์ cursor ด้วย cursor()

  • สร้างคำสั่ง SQL ที่เหมาะสม

  • รันคำสั่งด้วย execute()

  • commit การเปลี่ยนแปลงด้วย commit()

  • ปิดการเชื่อมต่อ

สมมติว่ามีตาราง Student:

+----------+---------+-----------+------------+
| Name     | Class   | City      | Marks      |
+----------+---------+-----------+------------+
| Karan    | 4       | Amritsar  | 95         |
| Sahil    | 6       | Amritsar  | 93         |
| Kriti    | 3       | Batala    | 88         |
| Khushi   | 9       | Delhi     | 90         |
| Kirat    | 5       | Delhi     | 85         |
+----------+---------+-----------+------------+

ตัวอย่าง

อัปเดตเมืองของ Kriti จาก Batala เป็น Kolkata และ commit

import mysql.connector
db = mysql.connector.connect(
    host="your_host",
    user="your_username",
    password="your_password",
    database="database_name"
)
cursor = db.cursor()
query = "UPDATE Students SET City='Kolkata' WHERE Name='Kriti'"
cursor.execute(query)
db.commit()
query = "SELECT * FROM Students"
cursor.execute(query)
for row in cursor:
    print(row)
db.close()

โค้ดอัปเดตชื่อเมืองของ Kriti และ commit การเปลี่ยนแปลง

ผลลัพธ์

('Karan', 4, 'Amritsar', 95)
('Sahil', 6, 'Amritsar', 93)
('Kriti', 3, 'Kolkata', 88)
('Amit', 9, 'Delhi', 90)
('Priya', 5, 'Delhi', 85)

หมายเหตุ

db.commit() สำคัญมาก ถ้าไม่ใช้ commit() การเปลี่ยนแปลงจะไม่เกิดขึ้นในตาราง