Python PostgreSQL - 建立資料庫



你可以使用 CREATE DATABASE 語句在 PostgreSQL 中建立一個數據庫。你可以在 PostgreSQL shell 提示符中執行此語句,指定要建立的資料庫名稱作為此命令的字尾。

語法

以下是 CREATE DATABASE 語句的語法。

CREATE DATABASE dbname;

示例

以下語句在 PostgreSQL 中建立一個名為 testdb 的資料庫。

postgres=# CREATE DATABASE testdb;
CREATE DATABASE

你可以使用 \l 命令列出 PostgreSQL 中的資料庫。如果你驗證資料庫列表,你將能找到如下所示的新建資料庫 −

postgres=# \l
                                                List of databases
   Name    | Owner    | Encoding |        Collate             |     Ctype   |
-----------+----------+----------+----------------------------+-------------+
mydb       | postgres | UTF8     | English_United States.1252 | ........... |
postgres   | postgres | UTF8     | English_United States.1252 | ........... |
template0  | postgres | UTF8     | English_United States.1252 | ........... |
template1  | postgres | UTF8     | English_United States.1252 | ........... |
testdb     | postgres | UTF8     | English_United States.1252 | ........... |
(5 rows)

你還可以使用命令形語句 createdb 在命令提示符中從 SQL 語句 CREATE DATABASE 來建立 PostgreSQL 中的資料庫。

C:\Program Files\PostgreSQL\11\bin> createdb -h localhost -p 5432 -U postgres sampledb
Password:

使用 Python 建立資料庫

psycopg2 的游標類提供了多種方法來執行各種 PostgreSQL 命令、獲取記錄和複製資料。你可以使用 Connection 類中的 cursor() 方法建立一個游標物件。

此類的 execute() 方法接收一個 PostgreSQL 查詢作為引數並執行該查詢。

因此,要在 PostgreSQL 中建立一個數據庫,請使用此方法執行 CREATE DATABASE 查詢。

示例

以下 python 示例在 PostgreSQL 資料庫中建立了一個名為 mydb 的資料庫。

import psycopg2

#establishing the connection

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

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

#Preparing query to create a database
sql = '''CREATE database mydb''';

#Creating a database
cursor.execute(sql)
print("Database created successfully........")

#Closing the connection
conn.close()

輸出

Database created successfully........
廣告