最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用psycopg2操作PostgreSQL數(shù)據(jù)庫的完全指南

 更新時間:2025年06月25日 09:18:47   作者:小龍在山東  
psycopg2 是 Python 中最流行的 PostgreSQL 數(shù)據(jù)庫適配器,它實現(xiàn)了 Python DB API 2.0 規(guī)范,同時提供了許多 PostgreSQL 特有的功能支持,下面我們來看看如何使用psycopg2操作PostgreSQL進行連接和增刪改查操作吧

安裝

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')
        
# 準備隨機數(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} 條隨機學生數(shù)據(jù)")


查詢數(shù)據(jù)

def get_students_as_dict(dbname, user, password, host='localhost', port=5432):
    """以字典形式返回學生數(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字典形式的學生數(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):
    """
    更新指定學生的單科成績
    
    參數(shù):
        student_id: 學生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"成功更新學生 {updated_row[1]} (ID: {updated_row[0]}) 的{subject.replace('_', '')}為 {updated_row[2]}")
        else:
            print(f"未找到ID為 {student_id} 的學生")
        
    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,  # 要更新的學生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ù)學生ID刪除記錄"""
    try:
        conn = psycopg2.connect(
            dbname=dbname,
            user=user,
            password=password,
            host=host,
            port=port
        )
        cursor = conn.cursor()
        
        # 先查詢學生是否存在
        cursor.execute("""
            SELECT name, class FROM students WHERE id = %s
        """, (student_id,))
        
        student = cursor.fetchone()
        
        if not student:
            print(f"未找到ID為 {student_id} 的學生")
            return
        
        # 確認刪除
        confirm = input(f"確定要刪除學生 {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"已刪除學生: ID {deleted_student[0]}, 姓名: {deleted_student[1]}, 班級: {deleted_student[2]}")
        else:
            print("刪除失敗,未找到該學生")
        
    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,  # 要刪除的學生ID
    host='localhost'
)

到此這篇關(guān)于Python使用psycopg2操作PostgreSQL數(shù)據(jù)庫的完全指南的文章就介紹到這了,更多相關(guān)Python psycopg2操作PostgreSQL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python實現(xiàn)網(wǎng)站注冊驗證碼生成類

    Python實現(xiàn)網(wǎng)站注冊驗證碼生成類

    這篇文章主要為大家詳細介紹了Python實現(xiàn)網(wǎng)站注冊驗證碼生成類,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • 使用wxpy實現(xiàn)自動發(fā)送微信消息功能

    使用wxpy實現(xiàn)自動發(fā)送微信消息功能

    這篇文章主要介紹了使用wxpy實現(xiàn)自動發(fā)送微信消息功能,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • Python淺拷貝與深拷貝用法實例

    Python淺拷貝與深拷貝用法實例

    這篇文章主要介紹了Python淺拷貝與深拷貝用法,實例分析了Python淺拷貝與深拷貝的功能與使用方法,需要的朋友可以參考下
    2015-05-05
  • Python中文件的讀取和寫入操作

    Python中文件的讀取和寫入操作

    這篇文章主要介紹了Python中文件的讀取和寫入操作,從文件中讀取數(shù)據(jù)的操作方法,本文通過實例文字相結(jié)合的形式給大家介紹的非常詳細,需要的朋友可以參考下
    2018-04-04
  • python基于socket進行端口轉(zhuǎn)發(fā)實現(xiàn)后門隱藏的示例

    python基于socket進行端口轉(zhuǎn)發(fā)實現(xiàn)后門隱藏的示例

    今天小編就為大家分享一篇python基于socket進行端口轉(zhuǎn)發(fā)實現(xiàn)后門隱藏的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • Python入門之Python中的循環(huán)語句

    Python入門之Python中的循環(huán)語句

    這段文章詳細介紹了Python編程中的循環(huán)語句,包括while循環(huán)、for循環(huán)和嵌套循環(huán),文章解釋了while循環(huán)的條件控制機制,強調(diào)避免死循環(huán)的重要性,闡述了for循環(huán)的遍歷特點和適用場景,并介紹了range函數(shù)句用于生成數(shù)字序列,最后通過示例展示了嵌套循環(huán)的應用
    2026-05-05
  • tensorflow生成多個tfrecord文件實例

    tensorflow生成多個tfrecord文件實例

    今天小編就為大家分享一篇tensorflow生成多個tfrecord文件實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • 淺析Python中的序列化存儲的方法

    淺析Python中的序列化存儲的方法

    這篇文章主要介紹了Python中的序列化存儲的方法,序列化存儲主要針對的是內(nèi)存和硬盤之間的寫入操作,需要的朋友可以參考下
    2015-04-04
  • 對tensorflow中tf.nn.conv1d和layers.conv1d的區(qū)別詳解

    對tensorflow中tf.nn.conv1d和layers.conv1d的區(qū)別詳解

    今天小編就為大家分享一篇對tensorflow中tf.nn.conv1d和layers.conv1d的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • 一文詳解NumPy數(shù)組迭代與合并

    一文詳解NumPy數(shù)組迭代與合并

    NumPy?數(shù)組迭代是訪問和處理數(shù)組元素的重要方法,它允許您逐個或成組地遍歷數(shù)組元素,NumPy?提供了多種函數(shù)來合并數(shù)組,用于將多個數(shù)組的內(nèi)容連接成一個新數(shù)組,本文給大家詳細介紹了NumPy數(shù)組迭代與合并,需要的朋友可以參考下
    2024-05-05

最新評論

南华县| 通江县| 哈巴河县| 泾阳县| 呼和浩特市| 乌鲁木齐市| 建昌县| 江门市| 保靖县| 祁连县| 济阳县| 奎屯市| 凤凰县| 云安县| 吉木乃县| 宁波市| 邻水| 孝感市| 太仆寺旗| 和林格尔县| 平舆县| 桃园市| 新兴县| 龙山县| 延津县| 壤塘县| 临海市| 乡宁县| 泾源县| 阜平县| 科技| 舟曲县| 华宁县| 铜山县| 广河县| 犍为县| 阿城市| 澄迈县| 嘉定区| 盐山县| 鸡泽县|