วิธีการ สร้างตารางข้อมูลในฐานข้อมูล Postgres ด้วย Module psycopg2

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: วิธีการ สร้างตารางข้อมูลในฐานข้อมูล Postgres ด้วย Module psycopg2

Re: วิธีการ สร้างตารางข้อมูลในฐานข้อมูล Postgres ด้วย Module psycopg2

โดย บุคคลทั่วไป » 08/11/2022 8:13 pm

ขอบคุณครับ ลองทำแล้วใช้ได้เลย

วิธีการ สร้างตารางข้อมูลในฐานข้อมูล Postgres ด้วย Module psycopg2

โดย MBMoo » 09/06/2020 3:20 pm

วิธีการ สร้างตารางข้อมูลในฐานข้อมูล 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 ในการ สร้าง ตาราง

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

sql = """CREATE TABLE  table_test_1(
            id serial NOT NULL,
            name character varying(20) NOT NULL,
            CONSTRAINT table_test_1_pkey PRIMARY KEY (id))"""
    cur.execute(sql)
เมื่อสร้างตาราวงสำเร็จ ให้แสดงผลตามที่เราต้องการ

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

   cur.execute(sql)
    con.commit()
    print('เรียบร้อย')

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

try:
    con = p.connect(database='test',user='postgres',password='01249')
    cur = con.cursor()
    # cur.execute('DROP TABLE IF EXISTS test_python')
    # print ('Drop test_python เรียบร้อย')

    sql = """CREATE TABLE  table_test_1(
            id serial NOT NULL,
            name character varying(20) NOT NULL,
            CONSTRAINT table_test_1_pkey PRIMARY KEY (id))"""
    cur.execute(sql)
    con.commit()
    print('เรียบร้อย')
except p.DatabaseError:
    print('Error %s' %p.DatabaseError)

if con:
    con.close()


ผลลัพธ์
Python Knowledge-1.png
Python Knowledge-1.png (634 ไบต์) Viewed 2092 times
Python Knowledge-2.png
Python Knowledge-2.png (7.27 KiB) Viewed 2092 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
วิธีการ เพิ่มข้อมูลลงฐานข้อมูล Postgres ด้วย Module psycopg2 viewtopic.php?f=144&t=67978
วิธีการ แก้ไขข้อมูลในฐานข้อมูล Postgres ด้วย Module psycopg2 viewtopic.php?f=144&t=67979
วิธีการ ลบข้อมูลออกจากฐานข้อมูล Postgres ด้วย Module psycopg2 viewtopic.php?f=144&t=67980

ข้างบน