บทความนี้แนะนำการใช้ PostgreSQL กับ Python ผ่านไลบรารี psycopg2
การเตรียมความพร้อม
- ติดตั้ง PostgreSQL และสร้างฐานข้อมูลผ่าน pgAdmin
- ติดตั้ง psycopg2:
pip install psycopg2
ขั้นตอนการเชื่อมต่อและใช้งาน
- Import
psycopg2 - เก็บข้อมูลเชื่อมต่อ (database, user, password) ในตัวแปร
- สร้าง connection ด้วย
psycopg2.connect() - สร้าง cursor เพื่อรันคำสั่ง SQL
- Execute query และ fetch ผลลัพธ์
- ปิด 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