ฟังก์ชั่น .execute() คือ Method ย่อยของ library psycopg2 โดยตัวฟังก์ชั่นจะทำหน้าที่ในการเรียกใช้คำสั่งของทาง SQL ในการ แสดง เพิ่ม ลบ แก้ไข ข้อมูลของทาง Database ด้วยภาษา Python ที่ใช้ฐานข้อมูลของ PostgreSQL วิธีการเขียนหลักๆ มีดังนี้
1.ทำการ import psycopg2
import psycopg2 as p
2.สร้างตัวแปรที่เชื่อมกับฐานข้อมูล
con = p.connect(
host='localhost',
database='ben01',
user='postgres',
password='postgres'
)
3.กำหนดตัวแปร cursor เพื่อทำการชี้ตำแหน่ง
cur = con.cursor ()
4.ทำการเรียกใช้ cur.execute() เพื่อ ใช้คำสั่งของ sql ในการจัดการข้อมูลของ database เช่น
cur.execute('SELECT version()')
total = cur.fetchall()
print(total)
จะทำการดึง version ของ database มาแสดง
ผลลัพธ์
ผลลัพธ์ แสดงข้อมูล version
หรือ
cur.execute("SELECT latest_version FROM ir_module_module where state = 'installed'") total = cur.fetchall()
print(total)
ผลลัพธ์
ศึกษาเพิ่มเติม