跳至页脚内容
PYTHON 帮助

psycopg2(开发人员如何使用)

psycopg2库是Python编程语言中流行的PostgreSQL数据库适配器。 它以其效率、线程安全性和Python DB API 2.0规范的完整实现而闻名。 让我们探讨其功能并查看一些代码示例。 Later in this article, we will learn about IronPDF, a PDF generation library from Iron Software.

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

代码解释

该脚本演示了使用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)。

  6. PDF生成:使用IronPDF从HTML内容生成PDF文档。 HTML内容包括标题和从users表中提取的数据的格式化表示。
  7. 文件保存:将生成的PDF文档保存为"Demopsycopg2.pdf"在当前目录中。
  8. 连接关闭:关闭数据库游标(cur)和数据库连接(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的全面功能,与现有的Web技术无缝集成。 使用IronPDF,开发人员可以高效地自动化生成报告、发票和其他文档,提升生产力和用户体验。 其功能包括交互式PDF表单、文本提取、合并和拆分PDF,以及添加诸如密码保护之类的安全功能。 IronPDF的多功能性和易用性使其成为开发人员在Python项目中实现PDF生成和操作功能的宝贵工具。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。