如何在 MySQL 資料庫中插入 Python 元組?


假設伺服器上存在名為 test 的 MySQL 資料庫,並且還建立了一個名為 employee 的表。該表有五個欄位 fname、lname、age、gender 和 salary。

包含記錄資料的元組物件定義為

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

要建立 MySQL  和 Python 3 之間的介面,你需要安裝 PyMySQL 模組。然後,你可以使用以下語句設定連線

import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","root","","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()

下一步是用元組中的資料設定插入查詢

sql="insert into employee values(%s,%s,%d,%s,%d)" %t1

現在,使用游標物件的 execute() 方法執行此查詢

cursor.execute(sql)

如果你檢查 employee 表的內容,它將顯示其中新增的記錄。

更新於: 2020 年 2 月 18 日

2 千次以上瀏覽

開啟你的 事業

透過完成該課程來獲得認證

開始
廣告
© . All rights reserved.