psycopg2(開發者使用方法)
psycopg2函式庫是一個流行的 Python 程式語言的 PostgreSQL 資料庫適配器。 它以其高效性、線程安全性和對 Python DB API 2.0 規範的完全實現而聞名。 讓我們來探索它的功能並看一些程式碼範例。 本文稍後將介紹IronPDF ,這是Iron Software出品的 PDF 產生庫。
Psycopg2 的設計兼顧高效能和安全性,使其適用於高度多執行緒的應用程式。 它的一些主要特點包括:
*線程安全:*多個線程可以共享同一個連接——能夠處理創建和銷毀大量遊標的多線程應用程式。 客戶端和伺服器端遊標:高效處理大型資料集。 非同步通訊和通知:支援非同步操作。 複製支援:使用 COPY TO 和 COPY FROM 有效率地批次載入資料。 適配系統:自動將 Python 類型適配到 PostgreSQL 類型;該軟體包自動轉換為符合的 Postgresql 資料類型。 相容於 Unicode 和 Python 3:**完全支援 Unicode 和 Python 3。
安裝
您可以使用 pip 安裝psycopg2 :
pip install psycopg2pip install psycopg2或者,您也可以在本機使用來源套件中的setup.py 檔案。 您可以從此處的源代碼庫取得原始碼包:
python setup.py build
sudo python setup.py installpython setup.py build
sudo python setup.py install對於不需要編譯器或外部函式庫的獨立軟體包,您可以使用 psycopg2-binary 軟體包:
pip install psycopg2-binarypip install psycopg2-binary基本用法
這裡有一個簡單的例子,可以幫助你開始使用 psycopg2。
連接到資料庫
首先,您需要連接到您的PostgreSQL資料庫:
import psycopg2
# Connect to your PostgreSQL database
conn = psycopg2.connect(
dbname="your_dbname",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
# Create a cursor object
cur = conn.cursor()import psycopg2
# Connect to your PostgreSQL database
conn = psycopg2.connect(
dbname="your_dbname",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
# Create a cursor object
cur = conn.cursor()執行查詢
您可以使用遊標物件執行 SQL 查詢:
# Execute a query
cur.execute("SELECT * FROM your_table")
# Fetch all results
rows = cur.fetchall()
# Print the results
for row in rows:
print(row)# Execute a query
cur.execute("SELECT * FROM your_table")
# Fetch all results
rows = cur.fetchall()
# Print the results
for row in rows:
print(row)插入數據
以下是如何向表格中插入資料:
# Insert data into a table
cur.execute(
"INSERT INTO your_table (column1, column2) VALUES (%s, %s)",
("value1", "value2")
)
# Commit the transaction
conn.commit()# Insert data into a table
cur.execute(
"INSERT INTO your_table (column1, column2) VALUES (%s, %s)",
("value1", "value2")
)
# Commit the transaction
conn.commit()關閉連接
完成後,別忘了關閉遊標和連線:
# Close the cursor and connection
cur.close()
conn.close()# Close the cursor and connection
cur.close()
conn.close()進階功能
使用 COPY 進行批次載入
COPY 命令對於批次載入資料非常有用:
# Use COPY to load data from a file
with open('data.csv', 'r') as f:
cur.copy_from(f, 'your_table', sep=',')
conn.commit()# Use COPY to load data from a file
with open('data.csv', 'r') as f:
cur.copy_from(f, 'your_table', sep=',')
conn.commit()非同步通知
您可以監聽來自資料庫的非同步通知:
# Listen for notifications
cur.execute("LISTEN your_channel")
# Wait for a notification
conn.poll()
while conn.notifies:
notify = conn.notifies.pop(0)
print("Got NOTIFY:", notify.payload)# Listen for notifications
cur.execute("LISTEN your_channel")
# Wait for a notification
conn.poll()
while conn.notifies:
notify = conn.notifies.pop(0)
print("Got NOTIFY:", notify.payload)IronPDF簡介
! psycopg2(開發者使用指南):圖 1 - IronPDF:Python PDF 庫
IronPDF是一個功能強大的 Python 庫,旨在利用 HTML、CSS、圖像和 JavaScript 創建、編輯和簽署 PDF 文件。 它提供商業級的效能,同時佔用記憶體極少。 主要特點包括:
HTML 轉 PDF:
將 HTML 檔案、HTML 字串和 URL 轉換為 PDF。 例如,使用 Chrome PDF 渲染器將網頁渲染為 PDF。
跨平台支援:
相容於各種 .NET 平台,包括 .NET Core、.NET Standard 和 .NET Framework。 它支援 Windows、Linux 和 macOS。
編輯和簽署:
設定屬性,使用密碼和權限添加安全性,並為您的 PDF 應用數位簽章。
頁面範本和設定:
使用頁首、頁尾、頁碼和可調式邊距自訂 PDF。 支援響應式佈局和自訂紙張尺寸。
標準符合性:
符合 PDF 標準,例如 PDF/A 和 PDF/UA。 它支援 UTF-8 字元編碼,並可處理圖像、CSS 和字體等資源。
使用 IronPDF 和 psycopg2 產生 PDF 文檔
import psycopg2
from ironpdf import *
# Apply your license key
License.LicenseKey = "Key"
# Connect to your local PostgreSQL database
conn = psycopg2.connect(
dbname="demo",
user="postgres",
password="postgres",
host="localhost",
port="5432"
)
# Create a cursor object
cur = conn.cursor()
# Create the users table if it doesn't already exist
cur.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
# Commit the transaction
conn.commit()
# Define the SQL statement for inserting data into the table
insert_query = '''
INSERT INTO users (id, name, age)
VALUES (%s, %s, %s)
'''
# Data to be inserted
user_data = [
(1, 'John', 25),
(2, 'Smith', 35),
(3, 'Tom', 29)
]
# Insert data into the table
for user in user_data:
cur.execute(insert_query, user)
# Commit the transaction
conn.commit()
# Execute a query to retrieve data from the users table
cur.execute("SELECT * FROM users")
# Fetch all results
rows = cur.fetchall()
# Initialize PDF renderer
renderer = ChromePdfRenderer()
# Create a PDF from HTML content
content = "<h1>Awesome Iron PDF with psycopg2</h1>"
content += "<p>Table data:</p>"
for row in rows:
print(row)
content += f"<p>{row}</p>"
# Close the cursor and connection
cur.close()
conn.close()
# Render HTML content as PDF
pdf = renderer.RenderHtmlAsPdf(content)
# Save the PDF to a file
pdf.SaveAs("Demopsycopg2.pdf")import psycopg2
from ironpdf import *
# Apply your license key
License.LicenseKey = "Key"
# Connect to your local PostgreSQL database
conn = psycopg2.connect(
dbname="demo",
user="postgres",
password="postgres",
host="localhost",
port="5432"
)
# Create a cursor object
cur = conn.cursor()
# Create the users table if it doesn't already exist
cur.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
# Commit the transaction
conn.commit()
# Define the SQL statement for inserting data into the table
insert_query = '''
INSERT INTO users (id, name, age)
VALUES (%s, %s, %s)
'''
# Data to be inserted
user_data = [
(1, 'John', 25),
(2, 'Smith', 35),
(3, 'Tom', 29)
]
# Insert data into the table
for user in user_data:
cur.execute(insert_query, user)
# Commit the transaction
conn.commit()
# Execute a query to retrieve data from the users table
cur.execute("SELECT * FROM users")
# Fetch all results
rows = cur.fetchall()
# Initialize PDF renderer
renderer = ChromePdfRenderer()
# Create a PDF from HTML content
content = "<h1>Awesome Iron PDF with psycopg2</h1>"
content += "<p>Table data:</p>"
for row in rows:
print(row)
content += f"<p>{row}</p>"
# Close the cursor and connection
cur.close()
conn.close()
# Render HTML content as PDF
pdf = renderer.RenderHtmlAsPdf(content)
# Save the PDF to a file
pdf.SaveAs("Demopsycopg2.pdf")程式碼解釋
這個腳本示範如何使用psycopg2與 PostgreSQL 資料庫互動、資料操作(建立、插入、檢索)以及與IronPDF整合以產生文件。
1.資料庫連線:使用psycopg2連接到名為"demo"的本機 PostgreSQL 資料庫,指定使用者驗證憑證和資料庫主機詳細資料。 2.建立表格:定義並執行 SQL 語句,建立名為users表(如果該表尚不存在)。此表包含id (整數,主鍵)、 name (文本,非空)和age (整數)列。 3.資料插入:使用參數化查詢( user_data )將資料行插入users表中。 每個元組包含id 、 name和age的值。 4.事務管理:在建立表格和插入資料後提交事務,以確保變更儲存到資料庫。 5.資料擷取:執行 SELECT 查詢從users表中取得所有行( SELECT * FROM users ),並擷取結果( rows )。
- PDF 產生:使用
IronPDF從 HTML 內容產生 PDF 文件。 HTML 內容包括標題和從users表格中取得的資料的格式化表示。 7.檔案儲存:將產生的 PDF 文件儲存為"Demopsycopg2.pdf"到目前目錄。 8.連線關閉:關閉資料庫遊標(cur)和資料庫連線(conn),以釋放資源並確保正確清理。
為了處理異常情況,請將腳本包裝在 try-catch 區塊中,以確保在發生查詢或連線問題時能夠處理所有錯誤操作。
輸出
psycopg2(開發者使用方法):圖 3 - 使用 psycopg2 儲存和檢索數據,同時 IronPDF 產生 PDF 報告的範例輸出
IronPDF 許可
IronPDF使用 Python 許可證金鑰運作。 IronPDF for Python 提供免費試用許可證金鑰,使用戶能夠在購買前測試其豐富的功能。
在使用 IronPDF 軟體包之前,請將許可證密鑰放在腳本的開頭:
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"from ironpdf import *
# Apply your license key
License.LicenseKey = "key"結論
Psycopg2 是一個強大且靈活的函式庫,用於在 Python 中與 PostgreSQL 資料庫進行互動。 其全面的功能集和高效的設計使其成為簡單和複雜資料庫操作的絕佳選擇。 IronPDF是一個強大的 Python 套件和函式庫,它可以直接從 Python 應用程式建立、操作和渲染 PDF 文件。 它提供了從 HTML 內容生成 PDF 的全面功能,並與現有的 Web 技術無縫整合。 透過 IronPDF,開發人員可以有效率地自動產生報告、發票和其他文檔,從而提高生產力和使用者體驗。 它的功能包括互動式 PDF 表單、文字擷取、合併和分割 PDF,以及添加密碼保護等安全功能。 IronPDF 的多功能性和易用性使其成為開發人員在 Python 專案中實現 PDF 生成和操作功能的寶貴工具。







