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........
廣告