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)文章!
相關(guān)文章
Python Numpy教程之排序,搜索和計數(shù)詳解
這篇文章主要為大家詳細(xì)介紹了Python?NumPy中排序,搜索和計數(shù)的實現(xiàn),文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Python有一定幫助,需要的可以參考一下2022-08-08使用pyshp包進(jìn)行shapefile文件修改的例子
今天小編就為大家分享一篇使用pyshp包進(jìn)行shapefile文件修改的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12利用python-pypcap抓取帶VLAN標(biāo)簽的數(shù)據(jù)包方法
今天小編就為大家分享一篇利用python-pypcap抓取帶VLAN標(biāo)簽的數(shù)據(jù)包方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07Python 實現(xiàn)任意區(qū)域文字識別(OCR)操作
這篇文章主要介紹了Python 實現(xiàn)任意區(qū)域文字識別(OCR)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03python?memory_profiler庫生成器和迭代器內(nèi)存占用的時間分析
這篇文章主要介紹了python?memory_profiler庫生成器和迭代器內(nèi)存占用的時間分析,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,感興趣的小伙伴可以參考一下2022-06-06