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

การ Insert Tuple ลงฐานข้อมูล MySQL ใน Python

สมมติฐาน: มีฐานข้อมูล MySQL ชื่อ test และตาราง employee ที่มีฟิลด์ fname, lname, age, gender, salary

ข้อมูล Tuple

t1 = ('Mac', 'Mohan', 20, 'M', 2000)

ติดตั้งและเชื่อมต่อ

# ติดตั้ง: pip install PyMySQL
import PyMySQL

# เปิดการเชื่อมต่อ
db = PyMySQL.connect("localhost", "root", "", "test")

# สร้าง cursor
cursor = db.cursor()

สร้างและรัน Query

# ใช้ parameterized query (ปลอดภัยกว่า string formatting)
sql = "INSERT INTO employee (fname, lname, age, gender, salary) VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, t1)

# commit การเปลี่ยนแปลง
db.commit()

# ปิดการเชื่อมต่อ
db.close()

⚠️ คำเตือนความปลอดภัย: ตัวอย่างเดิมใช้ string formatting % t1 ซึ่งเสี่ยงต่อ SQL Injection ควรใช้ parameterized query (placeholders %s และส่ง tuple เป็นอาร์กิวเมนต์ที่ 2 ของ execute()) แทน