如何將 Python 元組插入到 PostgreSql 資料庫中?
PostgreSql 資料庫預設安裝在埠號 5432 上。透過安裝 psycopg2 模組提供 PostgreSql 的 Python 介面。假設有測試資料庫和包含 fname、sname、age、gender 和 salary 欄位的 employee 表可用。
首先在 Python 指令碼中執行以下命令建立連線並獲取遊標物件。
import psycopg2 conn = psycopg2.connect(database = "test", user = "postgres", password = "pass123", host = "localhost", port = "5432") cur = conn.cursor()
要插入到 employee 中的資料儲存在元組物件的形式中
t1=('Mac', 'Mohan', 20, 'M', 2000)
接下來使用此元組設定插入查詢
sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
現在使用遊標物件執行此查詢
cursor.execute(sql)
此命令的結果將是 employee 表顯示在其中新增的新記錄。
廣告