Python 中的資料庫插入操作


當想要將記錄建立到資料庫表中時需要這樣做。

示例

以下示例執行 SQL INSERT 語句以建立一個記錄到 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()

上面的示例可以按如下方式編寫以動態地建立 SQL 查詢 -

#!/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()

示例

以下程式碼段是另一種形式的執行,你可以在其中直接傳遞引數 -

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

更新時間: 31-1 月 -2020

421 瀏覽量

開啟你的 職業

完成課程並獲得認證

入門
廣告
© . All rights reserved.