Python PostgreSQL - 建立表



你可以使用 CREATE TABLE 語句在 PostgreSQL 資料庫中建立新表。在執行此操作時,你需要指定表名、列名及其資料型別。

語法

以下是 PostgreSQL 中 CREATE TABLE 語句的語法。

CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

示例

以下示例在 PostgreSQL 中建立了一個名為 CRICKETERS 的表。

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Age INT,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255));
CREATE TABLE
postgres=#

你可以使用 \dt 命令獲取 PostgreSQL 資料庫中的表列表。在建立表後,如果你可以驗證表列表,你可以在其中看到新建立的表,如下所示 −

postgres=# \dt
         List of relations
Schema  | Name       | Type  | Owner
--------+------------+-------+----------
public  | cricketers | table | postgres
(1 row)
postgres=#

同樣,你可以按照如下所示使用 \d 獲取已建立表的描述 −

postgres=# \d cricketers
                        Table "public.cricketers"
Column          | Type                   | Collation | Nullable | Default
----------------+------------------------+-----------+----------+---------
first_name      | character varying(255) |           |          |
last_name       | character varying(255) |           |          |
age             | integer                |           |          |
place_of_birth  | character varying(255) |           |          |
country         | character varying(255) |           |          |

postgres=#

使用 Python 建立表

要使用 python 建立表,你需要使用 _pyscopg2_ 的遊標的 execute() 方法執行 CREATE TABLE 語句。

示例

以下 Python 示例建立一個名為 employee 的表。

import psycopg2

#Establishing the connection

conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT)'''
cursor.execute(sql)
print("Table created successfully........")

#Closing the connection
conn.close()

輸出

Table created successfully........
廣告