- Python & MySQL 教程
- Python & MySQL - 主頁
- Python & MySQL - 概述
- Python & MySQL - 環境設定
- Python & MySQL 示例
- Python & MySQL - 連線資料庫
- Python & MySQL - 建立資料庫
- Python & MySQL - 放棄資料庫
- Python & MySQL - 選擇資料庫
- Python & MySQL - 建立表
- Python & MySQL - 放棄表
- Python & MySQL - 插入記錄
- Python & MySQL - 選擇記錄
- Python & MySQL - 更新記錄
- Python & MySQL - 刪除記錄
- Python & MySQL - Where 子句
- Python & MySQL - Like 子句
- Python & MySQL - 分類資料
- Python & MySQL - 使用連線
- Python & MySQL - 執行事務
- Python & MySQL - 處理錯誤
- Python & MySQL 有用的資源
- Python & MySQL - 快速指南
- Python & MySQL - 有用的資源
- Python & MySQL - 討論
PHP & MySQL - 插入記錄示例
Python 使用 c.execute(q) 函式在表中插入一條或多條記錄,其中 c 是遊標,q 是要執行的插入查詢。
語法
# execute SQL query using execute() method.
cursor.execute(sql)
# commit the record
db.commit()
# get the row id for inserted record
print("ID:", cursor.lastrowid)
# print the number of records inserted
print(mycursor.rowcount, "records inserted.")
| 序號 | 引數 & 說明 |
|---|---|
| 1 | $sql 必需 - 在表中插入記錄的 SQL 查詢。 |
示例
嘗試下列示例在表中插入記錄 -
複製並貼上下列示例為 mysql_example.ty -
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = """INSERT INTO tutorials_tbl
(tutorial_title,tutorial_author, submission_date)
VALUES ('HTML 5', 'Robert', '2010-02-10'),
('Java', 'Julie', '2020-12-10'),
('JQuery', 'Julie', '2020-05-10')
"""
# execute SQL query using execute() method.
cursor.execute(sql)
# commit the record
db.commit()
# get the row id for inserted record
print("ID:", cursor.lastrowid)
# print the number of records inserted
print(cursor.rowcount, "records inserted.")
# disconnect from server
db.close()
輸出
使用 Python 執行 mysql_example.py 指令碼並驗證輸出。
ID: 5 3 records inserted.
廣告