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

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

 更新時(shí)間:2022年09月28日 10:42:59   作者:水w  
這篇文章主要介紹了Python讀取postgresql數(shù)據(jù)庫(kù)詳情,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下

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

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

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

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

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

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

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

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

 postgresql_connection.py的完整代碼為:

# 導(dǎo)入 psycopg2 模塊和 Error 對(duì)象
import psycopg2
from psycopg2 import DatabaseError
from configparser import ConfigParser
def read_db_config(filename='dbconfig.ini', section='postgresql'):
    """ 讀取數(shù)據(jù)庫(kù)配置文件,返回一個(gè)字典對(duì)象"""
    # 創(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ù)庫(kù)
        connection = psycopg2.connect(**db_config)
        cur = connection.cursor()    # 創(chuàng)建一個(gè)游標(biāo)
        cur.execute('SELECT version()')    # 獲取 PostgreSQL 版本號(hào)
        db_version = cur.fetchone()
        print("連接成功,PostgreSQL 服務(wù)器版本:", db_version)    # 輸出 PostgreSQL 版本
 
        # `在這里插入代碼片`
 
        cur.close()    # 關(guān)閉游標(biāo)
    except (Exception, DatabaseError) as e:
        print("連接 PostgreSQL 失敗:", e)
    finally:
        if connection is not None:    # 釋放數(shù)據(jù)庫(kù)連接
            connection.close()
            print("PostgreSQL 數(shù)據(jù)庫(kù)連接已關(guān)閉。")

(4)運(yùn)行程序,

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

執(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ù)庫(kù)連接已關(guān)閉。

二、查詢(xún)數(shù)據(jù)

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

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

# 導(dǎo)入 psycopg2 模塊和 Error 對(duì)象
import psycopg2
from psycopg2 import DatabaseError
from configparser import ConfigParser
 
def read_db_config(filename='dbconfig.ini', section='postgresql'):
    """ 讀取數(shù)據(jù)庫(kù)配置文件,返回一個(gè)字典對(duì)象
    """
    # 創(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ù)庫(kù)
        cur = connection.cursor()        # 創(chuàng)建一個(gè)游標(biāo)
 
        # 定義 SQL 語(yǔ)句
        sql = """ select id, name, age from users"""
        cur.execute(sql)        # 執(zhí)行 SQL 命令
        print("用戶(hù)數(shù)量:", cur.rowcount)
 
        # 獲取結(jié)果
        user = cur.fetchone()
        while user is not None:
            print(user)
            user = cur.fetchone()
 
        cur.close()        # 關(guān)閉游標(biāo)
    except (Exception, DatabaseError) as e:
        print("操作失?。?, e)
    finally:
        if connection is not None:        # 釋放數(shù)據(jù)庫(kù)連接
            connection.close()

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

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

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

到此這篇關(guān)于Python讀取postgresql數(shù)據(jù)庫(kù)詳情的文章就介紹到這了,更多相關(guān)Python讀取postgresql內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

昌邑市| 西安市| 东港市| 乌海市| 永济市| 洛隆县| 洛阳市| 郎溪县| 克什克腾旗| 祁连县| 依安县| 贵阳市| 砀山县| 尖扎县| 赤峰市| 六安市| 汨罗市| 莆田市| 开远市| 阳城县| 通河县| 清苑县| 桃园市| 铁力市| 巴中市| 六枝特区| 闵行区| 阳朔县| 安龙县| 太原市| 天祝| 文成县| 平山县| 房产| 视频| 呼和浩特市| 黄石市| 广水市| 巴塘县| 成都市| 昌图县|