跳至頁尾內容
PYTHON 幫助

psycopg2(開發人員工作原理)

這個psycopg2程式庫是Python程式語言的一個受歡迎的PostgreSQL資料庫適配器。 它以效率高、執行緒安全性強及完整實現Python DB API 2.0規範而聞名。 讓我們來探索它的功能並查看一些程式碼範例。 在本文的後面,我們將了解IronPDF,這是來自Iron Software的一個PDF生成程式庫。

Psycopg2被設計為高效和安全,適合用於大量多執行緒的應用程式。 它的一些主要功能包括:

  • 執行緒安全性:多個執行緒可以共享相同的連接——能夠處理建立和銷毀大量游標的多執行緒應用程式。
  • 客戶端與伺服器端游標:有效地處理大型資料集。
  • 異步通信和通知:支援對異步操作的支持。
  • COPY 支援:通過使用COPY TO和COPY FROM高效率批量載入資料。
  • 適應系統:自動將Python型別適應為PostgreSQL型別;此封包會自動轉換為匹配的PostgreSQL資料型別。
  • Unicode 和 Python 3 友好:完全支持Unicode和Python 3。

安裝

您可以使用pip安裝psycopg2

pip install psycopg2
pip install psycopg2
SHELL

或者,您可以在本地使用來源包中的setup.py。 您可以從這裡的源程式碼庫獲取來源包:

python setup.py build
sudo python setup.py install
python setup.py build
sudo python setup.py install
SHELL

對於不需要編譯器或外部庫的獨立套件,您可以使用psycopg2-binary套件:

pip install psycopg2-binary
pip install psycopg2-binary
SHELL

基本用法

這是一個簡單的範例來讓您開始使用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()
PYTHON

執行查詢

您可以使用游標物件來執行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)
PYTHON

插入資料

以下是如何將資料插入到表中:

# 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()
PYTHON

關閉連接

當您完成後,不要忘記關閉游標和連接:

# Close the cursor and connection
cur.close()
conn.close()
# Close the cursor and connection
cur.close()
conn.close()
PYTHON

進階特色

使用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()
PYTHON

异步通知

您可以監聽來自資料庫的異步通知:

# 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)
PYTHON

介紹 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")
PYTHON

程式碼說明

這個腳本展示了使用IronPDF進行文件生成的整合。

  1. 資料庫連接:使用psycopg2連接到名為"demo"的本地PostgreSQL資料庫,指定使用者驗證的憑據和資料庫主機的詳細資訊。
  2. 表建立:定義並執行SQL語句以建立名為age(整數)。
  3. 資料插入:使用參數化查詢users表中。 每個元組包含age的值。
  4. 事務管理:表建立和資料插入後提交事務以確保更改保存在資料庫中。
  5. 資料檢索:執行SELECT查詢以從rows

  6. PDF生成:使用IronPDF從HTML內容生成PDF文件。 HTML內容包括一個標題以及從users表中提取的資料的格式化表示。
  7. 文件保存:將生成的PDF文件保存為"Demopsycopg2.pdf"於當前目錄中。
  8. 連接關閉:關閉資料庫游標conn以釋放資源並確保正確清理。

為了異常處理,把腳本包在try-catch塊中,以確保所有錯誤操作都在出現查詢或連接問題時得到處理。

輸出

psycopg2 (對開發者的運作方式): 圖2 - 範例控制台輸出

PDF

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"
PYTHON

結論

Psycopg2是一個強大且靈活的程式庫,用於在Python中與PostgreSQL資料庫互動。 其全面的功能集和有效的設計使其成為簡單和複雜資料庫操作的絕佳選擇。 IronPDF是一個強大的Python套件和程式庫,使得能夠從Python應用程式中直接建立、操作和渲染PDF文件。 它提供了從HTML內容生成PDF的全面功能,並無縫整合現有的網路技術。 通過IronPDF,開發人員可以高效地自動化生成報告、發票和其他檔案,提升生產力和使用者體驗。 其功能包括互動式PDF表單、提取文字、合併和分割PDF,以及新增密碼保護等安全功能。 IronPDF的多功能性和易用性使其成為開發人員期望在其Python項目中實施PDF生成和操作功能的有價值工具。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話