ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีใช้ PostgreSQL ด้วยไพทอน คุณต้องติดตั้งบางสิ่งก่อนเข้าสู่บทช่วยสอน มาติดตั้งกันเลย
ติดตั้ง PostgreSQL พร้อมไกด์..
ติดตั้ง Python โมดูล psycopg2 สำหรับการเชื่อมต่อ PostgreSQL และการทำงาน เรียกใช้คำสั่งเพื่อติดตั้ง
pip install psycopg2
ตอนนี้ เปิด pgAdmin . และสร้างฐานข้อมูลตัวอย่าง ถัดไป ทำตามขั้นตอนด้านล่างเพื่อเริ่มต้นใช้งานฐานข้อมูล
- นำเข้าโมดูล psycopg2
- จัดเก็บชื่อฐานข้อมูล ชื่อผู้ใช้ และรหัสผ่านในตัวแปรแยกกัน
- ทำการเชื่อมต่อกับฐานข้อมูลโดยใช้ psycopg2.connect(database=name,user=name, password=password) วิธีการ
- อินสแตนซ์วัตถุเคอร์เซอร์เพื่อดำเนินการ SQL คำสั่ง
- สร้างคำค้นหาและดำเนินการด้วย cursor.execute(query) วิธีการ
- และรับข้อมูลโดยใช้ cursor.fetchall() วิธีถ้ามี
- ปิดการเชื่อมต่อโดยใช้ connection.close() วิธีการ
ตัวอย่าง
# importing the psycopg2 module
import psycopg2
# storing all the information
database = 'testing'
user = 'postgres'
password = 'C&o%Z?bc'
# connecting to the database
connection = psycopg2.connect(database=database, user=user, password=password)
# instantiating the cursor
cursor = connection.cursor()
# query to create a table
create_table = "CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCH
25) NOT NULL)"
# executing the query
cursor.execute(create_table)
# sample data to populate the database table
testing_members = ['Python', 'C', 'JavaScript', 'React', 'Django']
# query to populate the table testing_members
for testing_member in testing_members:
populate_db = f"INSERT INTO testing_members (name) VALUES ('{testing_member
cursor.execute(populate_db)
# saving the changes to the database
connection.commit()
# query to fetch all
fetch_all = "SELECT * FROM testing_members"
cursor.execute(fetch_all)
# fetching all the rows
rows = cursor.fetchall()
# printing the data
for row in rows:
print(f"{row[0]} {row[1]}")
# closing the connection
connection.close() ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
1 Python 2 C 3 JavaScript 4 React 5 Django
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น