Python PostgreSQL - 資料庫連線



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

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

SQL shell

使用 Python 建立連線

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

示例

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

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',
)
廣告