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

ดึง ID หลัง INSERT ใน MySQL ด้วย Python (pymysql)

ใช้ cursor.lastrowid (PyMySQL) หรือ connection.insert_id() (mysqlclient) หลังจาก Execute INSERT

ข้อกำหนดเบื้องต้น

  • MySQL 8.0+
  • Python 3.6+
  • PyMySQL: pip install PyMySQL หรือ mysqlclient: pip install mysqlclient

โค้ด Python (PyMySQL)

import pymysql

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    database='business',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

try:
    with conn.cursor() as cursor:
        sql = "INSERT INTO student (Name) VALUES (%s)"
        cursor.execute(sql, ('New Student',))
        conn.commit()
        
        # ดึง ID ที่เพิ่ง Insert
        new_id = cursor.lastrowid
        print(f"Inserted ID: {new_id}")
finally:
    conn.close()

ผลลัพธ์

Inserted ID: 4

MySQL Query ตรงๆ (สำหรับอ้างอิง)

mysql> SELECT * FROM student;
+------+-------+
| id   | Name  |
+------+-------+
| 1    | John  |
| 2    | Bob   |
| 3    | Smith |
+------+-------+

หลัง Insert ผ่าน Python ID ถัดไปคือ 4

mysqlclient (MySQLdb) ใช้วิธีเดียวกัน

import MySQLdb
conn = MySQLdb.connect(...)
cursor = conn.cursor()
cursor.execute("INSERT INTO student (Name) VALUES (%s)", ('New Student',))
conn.commit()
new_id = conn.insert_id()  # หรือ cursor.lastrowid ก็ได้
หมายเหตุ: ต้อง conn.commit() ก่อนถึงจะได้ lastrowid ถูกต้อง (เว้นแต่ Autocommit=True) และใช้ Parameterized Query (%s) เพื่อป้องกัน SQL Injection