日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python讀取postgresql數(shù)據(jù)庫詳情_python

作者:水w ? 更新時間: 2022-11-17 編程語言

一、讀取postgresql數(shù)據(jù)庫

(1)首先,我們需要安裝 psycopg 驅(qū)動。通過 pip 安裝最新的 psycopg

pip install psycopg2 -i https://pypi.tuna.tsinghua.edu.cn/simple

(2) 創(chuàng)建一個數(shù)據(jù)庫連接的配置文件 dbconfig.ini,添加以下內(nèi)容:

[postgresql]
host = [ip地址]
port = 5432
database = xxx
user = xxx
password = xxx

配置文件中存儲了數(shù)據(jù)庫的連接信息:主機、端口、數(shù)據(jù)庫、用戶以及密碼;我們需要按照自己的環(huán)境進行配置。

(3)然后,新建一個測試數(shù)據(jù)庫連接的 Python 文件 postgresql_connection.py,

文件目錄結(jié)構(gòu)為:

?postgresql_connection.py的完整代碼為:

# 導(dǎo)入 psycopg2 模塊和 Error 對象
import psycopg2
from psycopg2 import DatabaseError
from configparser import ConfigParser
def read_db_config(filename='dbconfig.ini', section='postgresql'):
    """ 讀取數(shù)據(jù)庫配置文件,返回一個字典對象"""
    # 創(chuàng)建解析器,讀取配置文件
    parser = ConfigParser()
    parser.read(filename)
 
    # 獲取 postgresql 部分的配置
    db = {}
    if parser.has_section(section):
        items = parser.items(section)
        for item in items:
            db[item[0]] = item[1]
    else:
        raise Exception('文件 {1} 中未找到 {0} 配置信息!'.format(section, filename))
    return db
 
if __name__ == '__main__':
    db_config = read_db_config()
    connection = None
 
    try:
        # 使用 psycopg2.connect 方法連接 PostgreSQL 數(shù)據(jù)庫
        connection = psycopg2.connect(**db_config)
        cur = connection.cursor()    # 創(chuàng)建一個游標
        cur.execute('SELECT version()')    # 獲取 PostgreSQL 版本號
        db_version = cur.fetchone()
        print("連接成功,PostgreSQL 服務(wù)器版本:", db_version)    # 輸出 PostgreSQL 版本
 
        # `在這里插入代碼片`
 
        cur.close()    # 關(guān)閉游標
    except (Exception, DatabaseError) as e:
        print("連接 PostgreSQL 失敗:", e)
    finally:
        if connection is not None:    # 釋放數(shù)據(jù)庫連接
            connection.close()
            print("PostgreSQL 數(shù)據(jù)庫連接已關(guān)閉。")

(4)運行程序,

  • 首先,我們導(dǎo)入了 psycopg2 驅(qū)動和解析配置文件的 configparser 模塊;
  • 然后,創(chuàng)建一個讀取配置文件的 read_db_config 函數(shù);
  • 接下來調(diào)用 psycopg2.connect 函數(shù)創(chuàng)建一個新的數(shù)據(jù)庫連接;
  • 然后通過連接對象的 cursor 函數(shù)創(chuàng)建一個新的游標,并且執(zhí)行查詢語句返回數(shù)據(jù)庫的版本;
  • 在此之后,調(diào)用游標對象的 fetchone() 方法獲取返回結(jié)果并打印信息;
  • 最后,調(diào)用 close() 方法關(guān)閉游標資源和數(shù)據(jù)庫連接對象。

執(zhí)行以上腳本,返回的信息如下:

連接成功,PostgreSQL 服務(wù)器版本: ('PostgreSQL 12.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit',)
PostgreSQL 數(shù)據(jù)庫連接已關(guān)閉。

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

游標對象提供了三種獲取返回結(jié)果的方法:fetchone() 獲取下一行數(shù)據(jù),fetchmany(size=cursor.arraysize) 獲取下一組數(shù)據(jù)行,fetchall() 返回全部數(shù)據(jù)行。

(1)我們創(chuàng)建一個新的文件 postgresql_query.py:

# 導(dǎo)入 psycopg2 模塊和 Error 對象
import psycopg2
from psycopg2 import DatabaseError
from configparser import ConfigParser
 
def read_db_config(filename='dbconfig.ini', section='postgresql'):
    """ 讀取數(shù)據(jù)庫配置文件,返回一個字典對象
    """
    # 創(chuàng)建解析器,讀取配置文件
    parser = ConfigParser()
    parser.read(filename)
 
    # 獲取 postgresql 部分的配置
    db = {}
    if parser.has_section(section):
        items = parser.items(section)
        for item in items:
            db[item[0]] = item[1]
    else:
        raise Exception('文件 {1} 中未找到 {0} 配置信息!'.format(section, filename))
 
    return db
 
 
if __name__ == '__main__':
    db_config = read_db_config()
    connection = None
 
    try:
        connection = psycopg2.connect(**db_config)        # 使用 psycopg2.connect 方法連接 PostgreSQL 數(shù)據(jù)庫
        cur = connection.cursor()        # 創(chuàng)建一個游標
 
        # 定義 SQL 語句
        sql = """ select id, name, age from users"""
        cur.execute(sql)        # 執(zhí)行 SQL 命令
        print("用戶數(shù)量:", cur.rowcount)
 
        # 獲取結(jié)果
        user = cur.fetchone()
        while user is not None:
            print(user)
            user = cur.fetchone()
 
        cur.close()        # 關(guān)閉游標
    except (Exception, DatabaseError) as e:
        print("操作失敗:", e)
    finally:
        if connection is not None:        # 釋放數(shù)據(jù)庫連接
            connection.close()

(2)游標對象的 rowcount 屬性代表了返回的數(shù)據(jù)行數(shù),fetchone() 方法返回一行數(shù)據(jù)或者 None,while 循環(huán)用于遍歷和打印查詢結(jié)果。由于 users 表中目前只有一行數(shù)據(jù),

執(zhí)行以上文件的結(jié)果如下:

用戶數(shù)量: 2
(1, 'lane', False)
(2, 'lane_dynamic', False)

原文鏈接:https://blog.csdn.net/qq_45956730/article/details/127069943

欄目分類
最近更新