Python進(jìn)行PostgreSQL數(shù)據(jù)庫連接的詳細(xì)使用指南
在Python中連接PostgreSQL數(shù)據(jù)庫,最常用的庫是psycopg2。以下是詳細(xì)的使用指南:
安裝psycopg2
首先需要安裝psycopg2庫:
pip install psycopg2 # 或者使用二進(jìn)制版本(安裝更快) pip install psycopg2-binary
基本連接與操作
1. 建立數(shù)據(jù)庫連接
import psycopg2
# 建立連接
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
# 創(chuàng)建游標(biāo)對象
cur = conn.cursor()
2. 執(zhí)行SQL查詢
# 執(zhí)行簡單查詢
cur.execute("SELECT * FROM your_table LIMIT 5;")
# 獲取結(jié)果
rows = cur.fetchall()
for row in rows:
print(row)
3. 執(zhí)行參數(shù)化查詢(防止SQL注入)
# 使用參數(shù)化查詢
user_id = 5
cur.execute("SELECT * FROM users WHERE id = %s;", (user_id,))
user = cur.fetchone()
print(user)
4. 插入數(shù)據(jù)
# 插入單條數(shù)據(jù)
cur.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id;",
('John Doe', 'john@example.com')
)
user_id = cur.fetchone()[0]
conn.commit() # 必須提交事務(wù)
print(f"插入的用戶ID: {user_id}")
???????# 批量插入
users_data = [
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com'),
('Charlie', 'charlie@example.com')
]
cur.executemany(
"INSERT INTO users (name, email) VALUES (%s, %s);",
users_data
)
conn.commit()5. 更新數(shù)據(jù)
cur.execute(
"UPDATE users SET email = %s WHERE id = %s;",
('new_email@example.com', 1)
)
conn.commit()
6. 刪除數(shù)據(jù)
cur.execute(
"DELETE FROM users WHERE id = %s;",
(5,)
)
conn.commit()
使用上下文管理器(推薦)
# 使用with語句自動管理連接
with psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="your_host"
) as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM users;")
for row in cur:
print(row)
# 不需要顯式調(diào)用commit()或close(),with語句會自動處理
使用連接池(適用于Web應(yīng)用)
對于Web應(yīng)用等需要頻繁連接數(shù)據(jù)庫的場景,可以使用連接池:
from psycopg2 import pool
???????# 創(chuàng)建連接池
connection_pool = pool.SimpleConnectionPool(
minconn=1,
maxconn=10,
dbname="your_database",
user="your_username",
password="your_password",
host="your_host"
)
# 從連接池獲取連接
conn = connection_pool.getconn()
cur = conn.cursor()
cur.execute("SELECT * FROM users;")
# ... 執(zhí)行操作 ...
???????# 將連接返回給連接池
connection_pool.putconn(conn)使用SQLAlchemy(ORM方式)
如果你更喜歡使用ORM,可以安裝SQLAlchemy:
pip install sqlalchemy psycopg2-binary
然后使用:
from sqlalchemy import create_engine, text
# 創(chuàng)建引擎
engine = create_engine('postgresql://user:password@localhost:5432/dbname')
# 執(zhí)行查詢
with engine.connect() as connection:
result = connection.execute(text("SELECT * FROM users;"))
for row in result:
print(row)
注意事項
始終記得提交事務(wù)(conn.commit())或回滾(conn.rollback())
使用參數(shù)化查詢防止SQL注入
操作完成后關(guān)閉游標(biāo)和連接
對于生產(chǎn)環(huán)境,考慮使用連接池
將數(shù)據(jù)庫憑據(jù)存儲在環(huán)境變量或配置文件中,不要硬編碼在代碼里
以上就是Python進(jìn)行PostgreSQL數(shù)據(jù)庫連接的詳細(xì)使用指南的詳細(xì)內(nèi)容,更多關(guān)于Python PostgreSQL數(shù)據(jù)庫連接的資料請關(guān)注腳本之家其它相關(guān)文章!
- Python連接數(shù)據(jù)庫的3種方法對比(SQLite\MySQL\PostgreSQL)
- 在Python中使用SQLite數(shù)據(jù)庫進(jìn)行增刪改查操作的代碼示例
- python連接sqlite3簡單用法完整例子
- Python中如何使用sqlite3操作SQLite數(shù)據(jù)庫詳解
- 利用Python連接MySQL超詳細(xì)實戰(zhàn)教程
- Python進(jìn)行SQLite和MySQL數(shù)據(jù)庫連接與操作的完整指南
- 使用python進(jìn)行PostgreSQL數(shù)據(jù)庫連接全過程
- Python連接PostgreSQL數(shù)據(jù)庫并查詢數(shù)據(jù)的詳細(xì)指南
- Python連接到PostgreSQL數(shù)據(jù)庫的方法詳解
- Python數(shù)據(jù)庫學(xué)習(xí)心得:SQLite、MySQL、PostgreSQL優(yōu)缺點
相關(guān)文章
pycharm激活碼免費(fèi)分享適用最新pycharm2020.2.3永久激活
免費(fèi)為大家分享Pycharm激活碼,適用最新版pycharm2020.2.3永久激活,pycharm2018,pycharm2019也可永久激活,可成功激活到2089年2020-11-11
深入剖析Python的爬蟲框架Scrapy的結(jié)構(gòu)與運(yùn)作流程
這篇文章主要介紹了Python的爬蟲框架Scrapy的結(jié)構(gòu)與運(yùn)作流程,并以一個實際的項目來講解Scrapy的原理機(jī)制,十分推薦!需要的朋友可以參考下2016-01-01
Pycharm中安裝wordcloud等庫失敗問題及終端通過pip安裝的Python庫如何添加到Pycharm解釋器中(
這篇文章主要介紹了Pycharm中安裝wordcloud等庫失敗問題及終端通過pip安裝的Python庫如何添加到Pycharm解釋器中,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2020-05-05
Python?Prometheus接口揭秘數(shù)據(jù)科學(xué)新技巧
本篇文章將分享Prometheus?API的基本概念到PromQL查詢語言的應(yīng)用,再到如何通過Python與Prometheus?API進(jìn)行無縫交互,通過豐富的示例代碼和詳細(xì)的講解,將解鎖使用Python進(jìn)行實時監(jiān)控的奇妙世界,為讀者打開更廣闊的數(shù)據(jù)分析視野2024-01-01

