
- Python 資料訪問教程
- Python 資料訪問 - 首頁
- Python MySQL
- Python MySQL - 簡介
- Python MySQL - 資料庫連線
- Python MySQL - 建立資料庫
- Python MySQL - 建立表
- Python MySQL - 插入資料
- Python MySQL - 查詢資料
- Python MySQL - WHERE 子句
- Python MySQL - ORDER BY 子句
- Python MySQL - 更新表
- Python MySQL - 刪除資料
- Python MySQL - 刪除表
- Python MySQL - LIMIT 子句
- Python MySQL - JOIN 操作
- Python MySQL - 遊標物件
- Python PostgreSQL
- Python PostgreSQL - 簡介
- Python PostgreSQL - 資料庫連線
- Python PostgreSQL - 建立資料庫
- Python PostgreSQL - 建立表
- Python PostgreSQL - 插入資料
- Python PostgreSQL - 查詢資料
- Python PostgreSQL - WHERE 子句
- Python PostgreSQL - ORDER BY 子句
- Python PostgreSQL - 更新表
- Python PostgreSQL - 刪除資料
- Python PostgreSQL - 刪除表
- Python PostgreSQL - LIMIT 子句
- PostgreSQL - JOIN 操作
- Python PostgreSQL - 遊標物件
- Python SQLite
- Python SQLite - 簡介
- Python SQLite - 建立連線
- Python SQLite - 建立表
- Python SQLite - 插入資料
- Python SQLite - 查詢資料
- Python SQLite - WHERE 子句
- Python SQLite - ORDER BY 子句
- Python SQLite - 更新表
- Python SQLite - 刪除資料
- Python SQLite - 刪除表
- Python SQLite - LIMIT 子句
- Python SQLite - JOIN 操作
- Python SQLite - 遊標物件
- Python MongoDB
- Python MongoDB - 簡介
- Python MongoDB - 建立資料庫
- Python MongoDB - 建立集合
- Python MongoDB - 插入文件
- Python MongoDB - 查詢
- Python MongoDB - 查詢
- Python MongoDB - 排序
- Python MongoDB - 刪除文件
- Python MongoDB - 刪除集合
- Python MongoDB - 更新
- Python MongoDB - LIMIT 子句
- Python 資料訪問資源
- Python 資料訪問 - 快速指南
- Python 資料訪問 - 有用資源
- Python 資料訪問 - 討論
Python PostgreSQL - 資料庫連線
PostgreSQL 提供了自己的 shell 來執行查詢。要與 PostgreSQL 資料庫建立連線,請確保已在系統中正確安裝它。開啟 PostgreSQL shell 提示符並傳遞伺服器、資料庫、使用者名稱和密碼等詳細資訊。如果提供的詳細資訊都正確,則會與 PostgreSQL 資料庫建立連線。
傳遞詳細資訊時,您可以使用 shell 建議的預設伺服器、資料庫、埠和使用者名稱。

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