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

เริ่มต้นใช้งาน psycopg2 กับ PostgreSQL ใน Python

บทความนี้แนะนำการใช้ PostgreSQL กับ Python ผ่านไลบรารี psycopg2

การเตรียมความพร้อม

  1. ติดตั้ง PostgreSQL และสร้างฐานข้อมูลผ่าน pgAdmin
  2. ติดตั้ง psycopg2: pip install psycopg2

ขั้นตอนการเชื่อมต่อและใช้งาน

  1. Import psycopg2
  2. เก็บข้อมูลเชื่อมต่อ (database, user, password) ในตัวแปร
  3. สร้าง connection ด้วย psycopg2.connect()
  4. สร้าง cursor เพื่อรันคำสั่ง SQL
  5. Execute query และ fetch ผลลัพธ์
  6. ปิด connection

ตัวอย่างโค้ดเต็ม

import psycopg2

database = 'testing'
user = 'postgres'
password = 'C&o%Z?bc'

connection = psycopg2.connect(database=database, user=user, password=password)
cursor = connection.cursor()

# สร้างตาราง
create_table = "CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCHAR(25) NOT NULL)"
cursor.execute(create_table)

# เพิ่มข้อมูล
testing_members = ['Python', 'C', 'JavaScript', 'React', 'Django']
for member in testing_members:
    populate_db = f"INSERT INTO testing_members (name) VALUES ('{member}')"
    cursor.execute(populate_db)
    connection.commit()

# Query และแสดงผล
fetch_all = "SELECT * FROM testing_members"
cursor.execute(fetch_all)
rows = cursor.fetchall()

for row in rows:
    print(f"{row[0]} {row[1]}")

connection.close()

ผลลัพธ์

1 Python
2 C
3 JavaScript
4 React
5 Django

ข้อควรระวัง: ในโปรดักชันจริง ควรใช้ Parameterized Queries (cursor.execute("INSERT ... VALUES (%s)", (member,))) เพื่อป้องกัน SQL Injection แทน f-string