Python讀取postgresql數(shù)據(jù)庫詳情
一、讀取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的完整代碼為:
# 導入 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 服務器版本:", db_version) # 輸出 PostgreSQL 版本 # `在這里插入代碼片` cur.close() # 關閉游標 except (Exception, DatabaseError) as e: print("連接 PostgreSQL 失?。?, e) finally: if connection is not None: # 釋放數(shù)據(jù)庫連接 connection.close() print("PostgreSQL 數(shù)據(jù)庫連接已關閉。")
(4)運行程序,
- 首先,我們導入了 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() 方法關閉游標資源和數(shù)據(jù)庫連接對象。
執(zhí)行以上腳本,返回的信息如下:
連接成功,PostgreSQL 服務器版本: ('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ù)庫連接已關閉。
二、查詢數(shù)據(jù)
游標對象提供了三種獲取返回結(jié)果的方法:fetchone() 獲取下一行數(shù)據(jù),fetchmany(size=cursor.arraysize) 獲取下一組數(shù)據(jù)行,fetchall() 返回全部數(shù)據(jù)行。
(1)我們創(chuàng)建一個新的文件 postgresql_query.py:
# 導入 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() # 關閉游標 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)
到此這篇關于Python讀取postgresql數(shù)據(jù)庫詳情的文章就介紹到這了,更多相關Python讀取postgresql內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Pandas處理DataFrame稀疏數(shù)據(jù)及維度不匹配數(shù)據(jù)分析詳解
這篇文章主要為大家介紹了Pandas處理DataFrame稀疏數(shù)據(jù)及維度不匹配數(shù)據(jù)分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02詳解python函數(shù)的閉包問題(內(nèi)部函數(shù)與外部函數(shù)詳述)
這篇文章主要介紹了python函數(shù)的閉包問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-05-05使用Python請求http/https時如何設置失敗重試次數(shù)
這篇文章主要介紹了使用Python請求http/https時如何設置失敗重試次數(shù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06Python爬蟲的兩套解析方法和四種爬蟲實現(xiàn)過程
本文想針對某一網(wǎng)頁對 python 基礎爬蟲的兩大解析庫( BeautifulSoup 和 lxml )和幾種信息提取實現(xiàn)方法進行分析,及同一網(wǎng)頁爬蟲的四種實現(xiàn)方式,需要的朋友參考下吧2018-07-07