Giả sử database test, bảng employee(fname, lname, age, gender, salary).
Chuẩn bị
pip install PyMySQL
Code mẫu
import pymysql
# Dữ liệu tuple
t1 = ('Mac', 'Mohan', 20, 'M', 2000)
# Kết nối
db = pymysql.connect(host="localhost", user="root", password="", database="test")
cursor = db.cursor()
# Câu lệnh INSERT với placeholder %s (an toàn chống SQL injection)
sql = "INSERT INTO employee (fname, lname, age, gender, salary) VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, t1)
db.commit()
print("Đã chèn:", cursor.rowcount, "record")
db.close()
Lưu ý quan trọng:
- Dùng
%scho tất cả kiểu dữ liệu (PyMySQL tự xử lý quoting). - Không dùng format string
%t1trực tiếp vào SQL (rủi ro injection). - Luôn
commit()sau INSERT/UPDATE/DELETE.