Python PostgreSQL - 資料庫連線



PostgreSQL 提供了自己的 shell 來執行查詢。要與 PostgreSQL 資料庫建立連線,請確保已在系統中正確安裝它。開啟 PostgreSQL shell 提示符並傳遞伺服器、資料庫、使用者名稱和密碼等詳細資訊。如果提供的詳細資訊都正確,則會與 PostgreSQL 資料庫建立連線。

傳遞詳細資訊時,您可以使用 shell 建議的預設伺服器、資料庫、埠和使用者名稱。

PostgreSQL Shell Prompt

使用 Python 建立連線

psycopg2 的 connection 類表示/處理連線的例項。您可以使用connect() 函式建立新的連線。它接受基本的連線引數,例如 dbname、user、password、host、port,並返回一個連線物件。使用此函式,您可以與 PostgreSQL 建立連線。

示例

以下 Python 程式碼演示瞭如何連線到現有資料庫。如果資料庫不存在,則會建立它,最後返回一個數據庫物件。PostgreSQL 的預設資料庫名稱為postrgre。因此,我們將其作為資料庫名稱提供。

import psycopg2

#establishing the connection
conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("select version()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()
Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)

輸出

Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)
廣告