網站首頁 編程語言 正文
一、讀取postgresql數據庫
(1)首先,我們需要安裝 psycopg 驅動。通過 pip 安裝最新的 psycopg
pip install psycopg2 -i https://pypi.tuna.tsinghua.edu.cn/simple
(2) 創建一個數據庫連接的配置文件 dbconfig.ini,添加以下內容:
[postgresql]
host = [ip地址]
port = 5432
database = xxx
user = xxx
password = xxx
配置文件中存儲了數據庫的連接信息:主機、端口、數據庫、用戶以及密碼;我們需要按照自己的環境進行配置。
(3)然后,新建一個測試數據庫連接的 Python 文件 postgresql_connection.py,
文件目錄結構為:
?postgresql_connection.py的完整代碼為:
# 導入 psycopg2 模塊和 Error 對象
import psycopg2
from psycopg2 import DatabaseError
from configparser import ConfigParser
def read_db_config(filename='dbconfig.ini', section='postgresql'):
""" 讀取數據庫配置文件,返回一個字典對象"""
# 創建解析器,讀取配置文件
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 數據庫
connection = psycopg2.connect(**db_config)
cur = connection.cursor() # 創建一個游標
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: # 釋放數據庫連接
connection.close()
print("PostgreSQL 數據庫連接已關閉。")
(4)運行程序,
- 首先,我們導入了 psycopg2 驅動和解析配置文件的 configparser 模塊;
- 然后,創建一個讀取配置文件的 read_db_config 函數;
- 接下來調用 psycopg2.connect 函數創建一個新的數據庫連接;
- 然后通過連接對象的 cursor 函數創建一個新的游標,并且執行查詢語句返回數據庫的版本;
- 在此之后,調用游標對象的 fetchone() 方法獲取返回結果并打印信息;
- 最后,調用 close() 方法關閉游標資源和數據庫連接對象。
執行以上腳本,返回的信息如下:
連接成功,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 數據庫連接已關閉。
二、查詢數據
游標對象提供了三種獲取返回結果的方法:fetchone() 獲取下一行數據,fetchmany(size=cursor.arraysize) 獲取下一組數據行,fetchall() 返回全部數據行。
(1)我們創建一個新的文件 postgresql_query.py:
# 導入 psycopg2 模塊和 Error 對象
import psycopg2
from psycopg2 import DatabaseError
from configparser import ConfigParser
def read_db_config(filename='dbconfig.ini', section='postgresql'):
""" 讀取數據庫配置文件,返回一個字典對象
"""
# 創建解析器,讀取配置文件
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 數據庫
cur = connection.cursor() # 創建一個游標
# 定義 SQL 語句
sql = """ select id, name, age from users"""
cur.execute(sql) # 執行 SQL 命令
print("用戶數量:", cur.rowcount)
# 獲取結果
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: # 釋放數據庫連接
connection.close()
(2)游標對象的 rowcount 屬性代表了返回的數據行數,fetchone() 方法返回一行數據或者 None,while 循環用于遍歷和打印查詢結果。由于 users 表中目前只有一行數據,
執行以上文件的結果如下:
用戶數量: 2
(1, 'lane', False)
(2, 'lane_dynamic', False)
原文鏈接:https://blog.csdn.net/qq_45956730/article/details/127069943
相關推薦
- 2023-12-15 elementui前端flex布局兼容IE10瀏覽器常用屬性使用
- 2022-09-19 golang圖片處理庫image基本操作_Golang
- 2022-10-21 React封裝全屏彈框的方法_React
- 2023-01-04 go?doudou應用中使用枚舉類型教程示例_Golang
- 2022-07-14 關于C#?dynamic裝箱問題_C#教程
- 2022-05-25 String.isEmpty() 方法使用報空指針異常?那怎么才能更好的判斷String返回值為空的
- 2022-04-21 R語言數據可視化繪圖Slope?chart坡度圖畫法_R語言
- 2022-08-24 K8S之StatefulSet有狀態服務詳解_云其它
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支