วิธีการ เพิ่มข้อมูลลงฐานข้อมูล Postgres ด้วย Module psycopg2

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
MBMoo
PHP VIP Members
PHP VIP Members
โพสต์: 25365
ลงทะเบียนเมื่อ: 04/06/2020 10:05 am

วิธีการ เพิ่มข้อมูลลงฐานข้อมูล Postgres ด้วย Module psycopg2

โพสต์ที่ยังไม่ได้อ่าน โดย MBMoo »

วิธีการ เพิ่มข้อมูลลงฐานข้อมูล Postgres ด้วย Module psycopg2 โดย ภาษา Python Postgres คือระบบจัดการฐานข้อมูลที่เหมาะกับการทำระบบ ERP โดย Postgres เป็นระบบจัดการฐานข้อมูลที่ตอนนี้เป็นที่นิยม และใช้กันอย่างแพร่หลาย

เริ่มจากติดตั้ง psycopg2

โค้ด: เลือกทั้งหมด

import psycopg2 as p
ทำการเชื่อมต่อ กับ postgresql

โค้ด: เลือกทั้งหมด

 con = p.connect(database='test',user='postgres',password='01249')
    cur = con.cursor()

หลังจากนั้นใช้ภาษา sql ในการ insert

โค้ด: เลือกทั้งหมด

sql = """INSERT INTO table_test_1 (name)
            VALUES ('bo')"""
             sql = sql.encode('utf-8')
เมื่อเพิ่มข้อมูลสำเร็จ ให้แสดงผลตามที่เราต้องการ

โค้ด: เลือกทั้งหมด

  try:
        cur.execute(sql)
        con.commit()
        print('เพิ่มข้อมูลเรียบร้อยแล้ว')
    except :
        con.rollback()
        print('เพิ่มข้อมูลผิดพลาด')

โค้ด: เลือกทั้งหมด

try:
    con = p.connect(database='test',user='postgres',password='01249')
    cur = con.cursor()
    sql = """INSERT INTO table_test_1 (name)
            VALUES ('bo')"""
    sql = sql.encode('utf-8')
    try:
        cur.execute(sql)
        con.commit()
        print('เพิ่มข้อมูลเรียบร้อยแล้ว')
    except :
        con.rollback()
        print('เพิ่มข้อมูลผิดพลาด')

except p.DatabaseError:
    print('Error %s' %p.DatabaseError)

if con:
    con.close()


ผลลัพธ์
Python Knowledge-1.png
Python Knowledge-1.png (1.23 KiB) Viewed 1999 times
Python Knowledge-2.png
Python Knowledge-2.png (6.23 KiB) Viewed 1999 times

หากต้องการศึกษาเรื่อง Postgres และ psycopg2 หรือ python เพิ่มเติม สามารถศึกษาได้จากในบนเรียนของ python vdo python
https://www.mindphp.com/vdo-tutorial-python.html
บทเรียน Python
https://www.mindphp.com/%E0%B8%9A%E0%B8 ... ython.html
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 45