網(wǎng)站首頁 編程語言 正文
一、讀取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
相關(guān)推薦
- 2022-10-23 C#中使用Microsoft?Unity記錄日志_C#教程
- 2022-08-15 Android?Gradle模塊依賴替換使用技巧_Android
- 2022-09-05 Go語言接口的用法詳解_Golang
- 2022-03-05 Flutter基本組件Basics?Widget學(xué)習(xí)_Android
- 2022-11-16 anaconda打開閃退的解決過程_python
- 2022-09-14 python與xml數(shù)據(jù)的交互詳解_python
- 2021-12-13 linux下AutoFs掛載服務(wù)安裝教程_Linux
- 2022-09-28 使用C語言實現(xiàn)三子棋小游戲_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支