Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การ Insert Tuple ลงฐานข้อมูล PostgreSQL ใน Python

PostgreSQL ใช้พอร์ต 5432 โดยค่าเริ่มต้น Python interface คือโมดูล psycopg2

ติดตั้งและเชื่อมต่อ

# pip install psycopg2-binary
import psycopg2

conn = psycopg2.connect(
    database="test",
    user="postgres",
    password="pass123",
    host="localhost",
    port="5432"
)
cur = conn.cursor()

ข้อมูลและ Query

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

# ใช้ parameterized query (psycopg2 ใช้ %s สำหรับทุกชนิด)
sql = "INSERT INTO employee (fname, lname, age, gender, salary) VALUES (%s, %s, %s, %s, %s)"
cur.execute(sql, t1)

conn.commit()
cur.close()
conn.close()

ข้อแตกต่างจาก MySQL: psycopg2 ใช้ %s สำหรับทุกชนิดข้อมูล (ไม่ใช้ %d สำหรับ integer) และต้อง conn.commit() โดยตรง