Computer >> Máy Tính >  >> Lập trình >> Python

Hoạt động CHÈN cơ sở dữ liệu bằng Python

Nó là bắt buộc khi bạn muốn tạo bản ghi của mình vào một bảng cơ sở dữ liệu.

Ví dụ

Ví dụ sau, thực thi câu lệnh SQL INSERT để tạo bản ghi vào bảng EMPLOYEE -

#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
   LAST_NAME, AGE, SEX, INCOME)
   VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()
# disconnect from server
db.close()

Ví dụ trên có thể được viết như sau để tạo các truy vấn SQL động -

#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
   LAST_NAME, AGE, SEX, INCOME) \
   VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
   ('Mac', 'Mohan', 20, 'M', 2000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()
# disconnect from server
db.close()

Ví dụ

Đoạn mã sau là một dạng thực thi khác mà bạn có thể truyền trực tiếp các tham số -

..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % \
   (user_id, password))
..................................