จากบทความที่แล้วการเขียน Python เพื่อทำการติดต่อฐานข้อมูล PostgreSQLที่เรากล่าวถึงขั้นตอนการเชื่อมต่อฐานข้อมูล
ในบทความนี้จะแนะนำการเขียน Python เพื่อสร้างตารางฐานข้อมูล หรือ Table ใน PostgreSQL
เริ่มกันเลย
1.ทำการเชื่อมต่อฐานข้อมูล **ขอข้ามวิธีการเชื่อมต่อฐานข้อมูล
2.เขียนโค้ดเพื่อทำการสร้างตารางขึ้นมา โดยใช้โค้ด แล้วทำการรัน
[code]
try:
sql = """ create table if not exists test_python (
id serial not null,
name_first character varying(100) not null,
name_last character varying(100) not null,
favorite_color character varying(1000) not null,
constraint test_python_pkey PRIMARY KEY (id)
) """
cur.execute(sql)
con.commit()
print ('สร้างตาราง test_python เรียบร้อยแล้ว')
except n.DatabaseError:
print ('Error %s' %n.DatabaseError)
if con:
con.close()
[/code]
จะได้ผลดังภาพ
[attachment=1]Selection_741.png[/attachment]
4. ในโปรแกรม pgAdmin ก็จะมีการสร้างตารางขึ้นมาเรียบร้อยแล้ว ดังภาพ
[attachment=0]Selection_740.png[/attachment]
เป็นยังไงกันบ้างครับสำหรับวิธีการเขียน Python เพื่อสร้างตารางในฐานข้อมูล PostgreSQL การสร้างตารางในฐานข้อมูลสามารถช่วยให้ผู้ใช้สามารถจัดการกับฐานข้อมูลได้
ศึกษาข้อมูลเพิ่มเติมได้ที่
การเพิ่มข้อมูลลงตาราง PostgreSQL ด้วย Python
ไพทอนสร้างตารางในฐานข้อมูล Mysql Python Create Table Mysql
เขียน Python สร้างตาราง Table ใน PostgresSQL
Moderators: mindphp, ผู้ดูแลกระดาน
-
- PHP Super Member
- Posts: 204
- Joined: 13/05/2019 10:03 am
Users browsing this forum: No registered users and 4 guests