Python使用psycopg2操作PostgreSQL數(shù)據(jù)庫的完全指南
安裝
pip install psycopg2-binary
連接數(shù)據(jù)庫
使用連接參數(shù)直接連接
import psycopg2
# 基本連接參數(shù)
conn_params = {
"dbname": "test",
"user": "postgres",
"password": "password",
"host": "localhost",
"port": "5432"
}
try:
conn = psycopg2.connect(**conn_params)
print("數(shù)據(jù)庫連接成功")
# 執(zhí)行數(shù)據(jù)庫操作...
except psycopg2.Error as e:
print(f"連接數(shù)據(jù)庫失敗: {e}")
finally:
if 'conn' in locals():
conn.close()
使用連接字符串 (DSN)
import psycopg2
# 連接字符串格式
dsn = "dbname=test user=postgres password=password host=localhost port=5432"
try:
conn = psycopg2.connect(dsn)
print("數(shù)據(jù)庫連接成功")
# 執(zhí)行數(shù)據(jù)庫操作...
except psycopg2.Error as e:
print(f"連接數(shù)據(jù)庫失敗: {e}")
finally:
if 'conn' in locals():
conn.close()
創(chuàng)建表
import psycopg2
conn = psycopg2.connect(host='127.0.0.1',
port='5432',
dbname="test",
user="postgres",
password="password")
cur = conn.cursor()
cur.execute("""
CREATE TABLE students (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
class VARCHAR(50) NOT NULL,
math_score NUMERIC(5, 2) CHECK (math_score >= 0 AND math_score <= 100),
english_score NUMERIC(5, 2) CHECK (english_score >= 0 AND english_score <= 100),
science_score NUMERIC(5, 2) CHECK (science_score >= 0 AND science_score <= 100),
history_score NUMERIC(5, 2) CHECK (history_score >= 0 AND history_score <= 100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
插入隨機數(shù)據(jù)
import psycopg2
import random
from faker import Faker
conn = psycopg2.connect(host='127.0.0.1',
port='5432',
dbname="test",
user="postgres",
password="password")
cursor = conn.cursor()
fake = Faker('zh_CN')
# 準(zhǔn)備隨機數(shù)據(jù)
classes = ['一年一班', '一年二班', '二年一班', '二年二班', '三年一班', '三年二班']
students = []
count = 10
for _ in range(count):
name = fake.name()
class_name = random.choice(classes)
math = round(random.uniform(50, 100), 1)
english = round(random.uniform(50, 100), 1)
science = round(random.uniform(50, 100), 1)
history = round(random.uniform(50, 100), 1)
students.append((name, class_name, math, english, science, history))
# 插入數(shù)據(jù)
cursor.executemany("""
INSERT INTO students
(name, class, math_score, english_score, science_score, history_score)
VALUES (%s, %s, %s, %s, %s, %s)
""", students)
conn.commit()
print(f"成功插入 {count} 條隨機學(xué)生數(shù)據(jù)")

查詢數(shù)據(jù)
def get_students_as_dict(dbname, user, password, host='localhost', port=5432):
"""以字典形式返回學(xué)生數(shù)據(jù)"""
try:
conn = psycopg2.connect(host=host,
port=port,
dbname=dbname,
user=user,
password=password)
# 使用DictCursor可以返回字典形式的結(jié)果
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT id, name, class,
math_score, english_score,
science_score, history_score
FROM students
LIMIT 3
""")
print("\n字典形式的學(xué)生數(shù)據(jù):")
for row in cursor:
# 可以直接通過列名訪問
print(dict(row))
except psycopg2.Error as e:
print(f"查詢數(shù)據(jù)時出錯: {e}")
finally:
if conn:
conn.close()
更改數(shù)據(jù)
import psycopg2
def update_student_score(dbname, user, password, student_id, subject, new_score, host='localhost', port=5432):
"""
更新指定學(xué)生的單科成績
參數(shù):
student_id: 學(xué)生ID
subject: 科目名稱 ('math_score', 'english_score', 'science_score', 'history_score')
new_score: 新成績 (0-100)
"""
try:
conn = psycopg2.connect(
dbname=dbname,
user=user,
password=password,
host=host,
port=port
)
cursor = conn.cursor()
# 驗證科目名稱
valid_subjects = ['math_score', 'english_score', 'science_score', 'history_score']
if subject not in valid_subjects:
raise ValueError(f"無效科目名稱,必須是: {', '.join(valid_subjects)}")
# 執(zhí)行更新
cursor.execute(f"""
UPDATE students
SET {subject} = %s
WHERE id = %s
RETURNING id, name, {subject}
""", (new_score, student_id))
updated_row = cursor.fetchone()
if updated_row:
conn.commit()
print(f"成功更新學(xué)生 {updated_row[1]} (ID: {updated_row[0]}) 的{subject.replace('_', '')}為 {updated_row[2]}")
else:
print(f"未找到ID為 {student_id} 的學(xué)生")
except psycopg2.Error as e:
print(f"更新數(shù)據(jù)時出錯: {e}")
conn.rollback()
except ValueError as e:
print(f"參數(shù)錯誤: {e}")
finally:
if conn:
conn.close()
# 使用示例
update_student_score(
dbname='test',
user='postgres',
password='password',
student_id=1, # 要更新的學(xué)生ID
subject='math_score', # 要更新的科目
new_score=95.5, # 新成績
host='localhost'
)
刪除數(shù)據(jù)
import psycopg2
def delete_student_by_id(dbname, user, password, student_id, host='localhost', port=5432):
"""根據(jù)學(xué)生ID刪除記錄"""
try:
conn = psycopg2.connect(
dbname=dbname,
user=user,
password=password,
host=host,
port=port
)
cursor = conn.cursor()
# 先查詢學(xué)生是否存在
cursor.execute("""
SELECT name, class FROM students WHERE id = %s
""", (student_id,))
student = cursor.fetchone()
if not student:
print(f"未找到ID為 {student_id} 的學(xué)生")
return
# 確認(rèn)刪除
confirm = input(f"確定要刪除學(xué)生 {student[0]} (班級: {student[1]}) 嗎? (y/n): ")
if confirm.lower() != 'y':
print("刪除操作已取消")
return
# 執(zhí)行刪除
cursor.execute("""
DELETE FROM students
WHERE id = %s
RETURNING id, name, class
""", (student_id,))
deleted_student = cursor.fetchone()
if deleted_student:
conn.commit()
print(f"已刪除學(xué)生: ID {deleted_student[0]}, 姓名: {deleted_student[1]}, 班級: {deleted_student[2]}")
else:
print("刪除失敗,未找到該學(xué)生")
except psycopg2.Error as e:
print(f"刪除數(shù)據(jù)時出錯: {e}")
conn.rollback()
finally:
if conn:
conn.close()
# 使用示例
delete_student_by_id(
dbname='test',
user='postgres',
password='password',
student_id=3, # 要刪除的學(xué)生ID
host='localhost'
)
到此這篇關(guān)于Python使用psycopg2操作PostgreSQL數(shù)據(jù)庫的完全指南的文章就介紹到這了,更多相關(guān)Python psycopg2操作PostgreSQL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用smtplib?實現(xiàn)單發(fā)和群發(fā)郵件驗證碼
這篇文章主要介紹了Python使用smtplib?實現(xiàn)單發(fā)和群發(fā)郵件驗證碼,文章通過使用?smtplib?模塊在?Python?中發(fā)送電子郵件,需要的小伙伴可以參考一下2022-05-05
Deepsort + Yolo 實現(xiàn)行人檢測和軌跡追蹤的方法
這篇文章主要介紹了Deepsort + Yolo 實現(xiàn)行人檢測和軌跡追蹤,本項目通過采用深度學(xué)習(xí)方法實現(xiàn)YOLO算法行人檢測和deepsort算法對人員定位的和軌跡跟蹤,需要的朋友可以參考下2021-09-09
如何用Python和JS實現(xiàn)的Web SSH工具
這篇文章主要介紹了如何用Python和JS實現(xiàn)的Web SSH工具,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)在字典中將鍵映射到多個值上的方法
這篇文章主要介紹了Python在字典中將鍵映射到多個值上的方法,涉及Python針對字典的相關(guān)映射與初始化相關(guān)操作技巧,需要的朋友可以參考下2018-02-02
python安裝包出現(xiàn)Retrying?(Retry(total=4,?connect=None,?read=No
這篇文章主要給大家介紹了關(guān)于python安裝包出現(xiàn)Retrying?(Retry(total=4,?connect=None,?read=None,?redirect=None,?status=None))問題的解決方法,需要的朋友可以參考下2022-09-09

