查詢Hologres或postgresql中的數據

因Hologres使用postgresql的語法.所以兩者查詢一樣.

方案1:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;/*** 一個使用簡單連接池管理PostgreSQL連接的工具類。*/
public class PostgresConnectionUtil {private static final String URL = "jdbc:postgresql://hgprecn-cn-******"; //holo數據庫鏈接地址private static final String USER = "xxxx"; // 數據庫登錄用戶private static final String PASSWORD = "yyyy"; // 數據庫用戶密碼private static final int INITIAL_POOL_SIZE = 10; // 初始化連接數private static final List<Connection> connectionPool = new ArrayList<>(INITIAL_POOL_SIZE);private static final List<Connection> usedConnections = new ArrayList<>();static {try {for (int i = 0; i < INITIAL_POOL_SIZE; i++) {connectionPool.add(createConnection());}} catch (SQLException e) {e.printStackTrace();}}/*** 創建一個新的PostgreSQL數據庫連接。** @return 一個新的數據庫連接* @throws SQLException 如果發生數據庫訪問錯誤*/private static Connection createConnection() throws SQLException {return DriverManager.getConnection(URL, USER, PASSWORD);}/*** 從連接池中獲取一個連接。** @return 一個PostgreSQL數據庫連接* @throws SQLException 如果發生數據庫訪問錯誤*/public static synchronized Connection getConnection() throws SQLException {if (connectionPool.isEmpty()) {connectionPool.add(createConnection());}Connection connection = connectionPool.remove(connectionPool.size() - 1);usedConnections.add(connection);return connection;}/*** 將連接釋放回連接池。** @param connection 要釋放的連接*/public static synchronized void releaseConnection(Connection connection) {connectionPool.add(connection);usedConnections.remove(connection);}/*** 關閉連接池中的所有連接。*/public static synchronized void closeAllConnections() {for (Connection connection : connectionPool) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}for (Connection connection : usedConnections) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}/*** 獲取可用連接的數量。** @return 可用連接的數量*/public static int getAvailableConnections() {return connectionPool.size();}
}


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class PostgresConnectionExample {public static void main(String[] args) {
//        // 插入操作
//        String insertQuery = "INSERT INTO test_table (name) VALUES (?)";
//        try (Connection connection = PostgresConnectionUtil.getConnection();
//             PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
//
//            preparedStatement.setString(1, "John Doe");
//            int rowsAffected = preparedStatement.executeUpdate();
//            System.out.printf("Inserted %d row(s)%n", rowsAffected);
//
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//
//        // 更新操作
//        String updateQuery = "UPDATE test_table SET name = ? WHERE id = ?";
//        try (Connection connection = PostgresConnectionUtil.getConnection();
//             PreparedStatement preparedStatement = connection.prepareStatement(updateQuery)) {
//
//            preparedStatement.setString(1, "Jane Doe");
//            preparedStatement.setInt(2, 1);
//            int rowsAffected = preparedStatement.executeUpdate();
//            System.out.printf("Updated %d row(s)%n", rowsAffected);
//
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }// 查詢操作
//        String selectQuery = "SELECT action_date,company_key FROM t_ads_application_company_persona_erp_trend";String selectQuery = "select * from test_table limit 3";try (Connection connection = PostgresConnectionUtil.getConnection();PreparedStatement preparedStatement = connection.prepareStatement(selectQuery);ResultSet resultSet = preparedStatement.executeQuery()) {while (resultSet.next()) {
//                String actionDate = resultSet.getString("action_date");
//                Long companyKey = resultSet.getLong("company_key");
//                System.out.printf("ID: %d, Name: %s%n", actionDate, companyKey);Long id = resultSet.getLong("id");Long teamId = resultSet.getLong("team_id");System.out.printf("ID: %d, Name: %s%n", id, teamId);}} catch (SQLException e) {e.printStackTrace();}//        // 刪除操作
//        String deleteQuery = "DELETE FROM test_table WHERE id = ?";
//        try (Connection connection = PostgresConnectionUtil.getConnection();
//             PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery)) {
//
//            preparedStatement.setInt(1, 1);
//            int rowsAffected = preparedStatement.executeUpdate();
//            System.out.printf("Deleted %d row(s)%n", rowsAffected);
//
//        } catch (SQLException e) {
//            e.printStackTrace();
//        } finally {
//            // 釋放連接回連接池
//            PostgresConnectionUtil.closeAllConnections();
//        }}
}

方案2:

import com.hupun.luban.holo.datasource.HoloDataSourceProperty;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.Date;
import java.util.*;

@Component
public class HologresUtils {

? ? private static final Log logger = LogFactory.getLog(HologresUtils.class);
? ? private BasicDataSource holoDataSource;

? ? @Autowired
? ? private HoloDataSourceProperty holoDataSourceProperty;

? ? @PostConstruct
? ? public BasicDataSource initHoloDataSource() {
? ? ? ? if (holoDataSource == null) {
? ? ? ? ? ? BasicDataSource ds = new BasicDataSource();
? ? ? ? ? ? ds.setUrl(holoDataSourceProperty.getUrl());
? ? ? ? ? ? ds.setUsername(holoDataSourceProperty.getUsername());
? ? ? ? ? ? ds.setPassword(holoDataSourceProperty.getPassword()); ? ? ? ? ? ?
? ? ? ? ? ? ds.setDriverClassName("org.postgresql.Driver");
? ? ? ? ? ? ds.setMinIdle(3); // 最小空閑數
? ? ? ? ? ? ds.setMaxIdle(5); //最大空閑數
? ? ? ? ? ? ds.setMaxOpenPreparedStatements(100);
? ? ? ? ? ? ds.setMaxTotal(5); //最大連接數
? ? ? ? ? ? ds.setMinEvictableIdleTimeMillis(300000); // 最小空閑時間
? ? ? ? ? ? ds.setMaxConnLifetimeMillis(7200000); // 最大空閑時間
? ? ? ? ? ? ds.setTimeBetweenEvictionRunsMillis(60000); // 休眠時間
? ? ? ? ? ? ds.setRemoveAbandonedOnBorrow(true);
? ? ? ? ? ? ds.setRemoveAbandonedTimeout(300);
? ? ? ? ? ? ds.setLogAbandoned(true);
? ? ? ? ? ? ds.setValidationQuery("SELECT 1");
? ? ? ? ? ? ds.setValidationQueryTimeout(2);
? ? ? ? ? ? ds.setDefaultQueryTimeout(120); // 默認查詢超時時間
? ? ? ? ? ? holoDataSource = ds;
? ? ? ? }
? ? ? ? return holoDataSource;
? ? }

? ? public BasicDataSource getHoloDataSource() {
? ? ? ? return holoDataSource;
? ? }

? ? public void setHoloDataSource(BasicDataSource holoDataSource) {
? ? ? ? this.holoDataSource = holoDataSource;
? ? }

? ? public HoloDataSourceProperty getHoloDataSourceProperty() {
? ? ? ? return holoDataSourceProperty;
? ? }

? ? public void setHoloDataSourceProperty(HoloDataSourceProperty holoDataSourceProperty) {
? ? ? ? this.holoDataSourceProperty = holoDataSourceProperty;
? ? }

? ? /**
? ? ?* 查詢
? ? ?* @param business 業務名稱
? ? ?* @param sql ? ? ?查詢語句
? ? ?* @param clazz ? ?結果類型
? ? ?* @param timeout ?超時時間
? ? ?* @return 結果列表
? ? ?*/
? ? public <T> List<T> query(String business, String sql, Class<T> clazz, int timeout) {
? ? ? ? List<T> results = new ArrayList<>();
? ? ? ? Connection connection = null;
? ? ? ? Statement statement = null;
? ? ? ? ResultSet resultSet = null;

? ? ? ? try {
? ? ? ? ? ? connection = holoDataSource.getConnection();
? ? ? ? ? ? statement = connection.createStatement();
? ? ? ? ? ? statement.setQueryTimeout(timeout);
? ? ? ? ? ? resultSet = statement.executeQuery(sql);

? ? ? ? ? ? ResultSetMetaData metaData = resultSet.getMetaData();
? ? ? ? ? ? int columnCount = metaData.getColumnCount();

? ? ? ? ? ? if (columnCount == 1) {
? ? ? ? ? ? ? ? results = handleSingleColumnResult(resultSet, metaData, clazz);
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? results = handleMultiColumnResult(resultSet, clazz);
? ? ? ? ? ? }
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? logger.error(business + "holo查詢異常,sql={"+sql+"}", e);
? ? ? ? ? ? cancelQuery(statement);
? ? ? ? } finally {
? ? ? ? ? ? closeResources(resultSet, statement, connection);
? ? ? ? }

? ? ? ? return results;
? ? }

? ? private <T> List<T> handleSingleColumnResult(ResultSet resultSet, ResultSetMetaData metaData, Class<T> clazz) throws SQLException {
? ? ? ? List<T> results = new ArrayList<>();
? ? ? ? String columnName = metaData.getColumnName(1);

? ? ? ? while (resultSet.next()) {
? ? ? ? ? ? Object value = extractValue(resultSet, columnName, clazz);
? ? ? ? ? ? @SuppressWarnings("unchecked")
? ? ? ? ? ? T castedValue = (T) value;
? ? ? ? ? ? results.add(castedValue);
? ? ? ? }
? ? ? ? return results;
? ? }

? ? private <T> List<T> handleMultiColumnResult(ResultSet resultSet, Class<T> clazz) throws Exception {
? ? ? ? List<T> results = new ArrayList<>();

? ? ? ? if (Map.class.isAssignableFrom(clazz)) {
? ? ? ? ? ? @SuppressWarnings("unchecked")
? ? ? ? ? ? List<T> mapResults = (List<T>) queryAsMap(resultSet);
? ? ? ? ? ? results.addAll(mapResults);
? ? ? ? } else {
? ? ? ? ? ? Field[] fields = clazz.getDeclaredFields();
? ? ? ? ? ? Map<String, Field> fieldMap = new HashMap<>();
? ? ? ? ? ? for (Field field : fields) {
? ? ? ? ? ? ? ? fieldMap.put(field.getName(), field);
? ? ? ? ? ? ? ? field.setAccessible(true);
? ? ? ? ? ? }

? ? ? ? ? ? while (resultSet.next()) {
? ? ? ? ? ? ? ? T instance = clazz.getDeclaredConstructor().newInstance();
? ? ? ? ? ? ? ? for (Map.Entry<String, Field> entry : fieldMap.entrySet()) {
? ? ? ? ? ? ? ? ? ? String fieldName = entry.getKey();
? ? ? ? ? ? ? ? ? ? Field field = entry.getValue();
? ? ? ? ? ? ? ? ? ? Object value = extractValue(resultSet, fieldName, field.getType());
? ? ? ? ? ? ? ? ? ? field.set(instance, value);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? results.add(instance);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return results;
? ? }

? ? private Object extractValue(ResultSet resultSet, String columnName, Class<?> fieldType) throws SQLException {
? ? ? ? Object value;
? ? ? ? if (fieldType == String.class) {
? ? ? ? ? ? value = resultSet.getString(columnName);
? ? ? ? } else if (fieldType == Integer.class || fieldType == int.class) {
? ? ? ? ? ? value = resultSet.getInt(columnName);
? ? ? ? } else if (fieldType == Long.class || fieldType == long.class) {
? ? ? ? ? ? value = resultSet.getLong(columnName);
? ? ? ? } else if (fieldType == Double.class || fieldType == double.class) {
? ? ? ? ? ? value = resultSet.getDouble(columnName);
? ? ? ? } else if (fieldType == Boolean.class || fieldType == boolean.class) {
? ? ? ? ? ? value = resultSet.getBoolean(columnName);
? ? ? ? } else if (fieldType == Date.class) {
? ? ? ? ? ? value = resultSet.getDate(columnName);
? ? ? ? } else if (fieldType == Timestamp.class) {
? ? ? ? ? ? value = resultSet.getTimestamp(columnName);
? ? ? ? } else {
? ? ? ? ? ? logger.error("類型不匹配");
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? return value;
? ? }

? ? private void cancelQuery(Statement statement) {
? ? ? ? if (statement != null) {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? statement.cancel();
? ? ? ? ? ? } catch (SQLException e) {
? ? ? ? ? ? ? ? logger.error("holo取消查詢異常,error={"+e.getMessage()+"}");
? ? ? ? ? ? }
? ? ? ? }
? ? }

? ? private void closeResources(ResultSet resultSet, Statement statement, Connection connection) {
? ? ? ? try {
? ? ? ? ? ? if (resultSet != null) {
? ? ? ? ? ? ? ? resultSet.close();
? ? ? ? ? ? }
? ? ? ? ? ? if (statement != null) {
? ? ? ? ? ? ? ? statement.close();
? ? ? ? ? ? }
? ? ? ? ? ? if (connection != null) {
? ? ? ? ? ? ? ? connection.close();
? ? ? ? ? ? }
? ? ? ? } catch (SQLException ignored) {
? ? ? ? }
? ? }

? ? private List<Map<String, Object>> queryAsMap(ResultSet resultSet) throws SQLException {
? ? ? ? List<Map<String, Object>> results = new ArrayList<>();
? ? ? ? ResultSetMetaData metaData = resultSet.getMetaData();
? ? ? ? int columnCount = metaData.getColumnCount();

? ? ? ? while (resultSet.next()) {
? ? ? ? ? ? Map<String, Object> row = new HashMap<>();
? ? ? ? ? ? for (int i = 1; i <= columnCount; i++) {
? ? ? ? ? ? ? ? String columnName = metaData.getColumnName(i);
? ? ? ? ? ? ? ? Object value = resultSet.getObject(i);
? ? ? ? ? ? ? ? row.put(columnName, value);
? ? ? ? ? ? }
? ? ? ? ? ? results.add(row);
? ? ? ? }
? ? ? ? return results;
? ? }
}
?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/76871.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/76871.shtml
英文地址,請注明出處:http://en.pswp.cn/web/76871.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

OpenBayes 一周速覽|EasyControl 高效控制 DiT 架構,助力吉卜力風圖像一鍵生成;TripoSG 單圖秒變高保真 3D 模型

公共資源速遞 10 個教程&#xff1a; * 一鍵部署 R1-OneVision * UNO&#xff1a;通用定制化圖像生成 * TripoSG&#xff1a;單圖秒變高保真 3D * 使用 VASP 進行機器學習力場訓練 * InfiniteYou 高保真圖像生成 Demo * VenusFactory 蛋白質工程設計平臺 * Qwen2.5-0mni…

中興云電腦W102D_晶晨S905X2_2+16G_mt7661無線_安卓9.0_線刷固件包

中興云電腦W102D_晶晨S905X2_216G_mt7661無線_安卓9.0_線刷固件包 準備工作&#xff1a; 工具和設備在開始刷機之前&#xff0c;確保你已經準備好以下物品&#xff1a;雙公頭USB線&#xff1a;選擇一根30-50厘米長的USB線&#xff0c;長度適中&#xff0c;方便操作&#xff0c;…

Rust 學習筆記:安裝 Rust

Rust 學習筆記&#xff1a;安裝 Rust Rust 學習筆記&#xff1a;安裝 Rust在 Windows 上安裝 Rust命令行創建 Rust 項目在 Mac/Linux 上安裝 Rust一些命令升級卸載cargo -hrustc -h 安裝 RustRoverrust-analyzer Rust 學習筆記&#xff1a;安裝 Rust 在 Windows 上安裝 Rust …

Opencv圖像處理:輪廓檢測、輪廓近似、繪制外接圓外接矩形

文章目錄 一、圖像輪廓檢測1、比較2、常見的輪廓檢測方法1&#xff09;基于梯度的方法2&#xff09;基于邊緣檢測器的方法3&#xff09;基于閾值的方法 3、查找輪廓與繪制輪廓4、參數解釋4、代碼解釋1&#xff09;讀取原圖像灰度圖并用二值化顯示2&#xff09;輪廓繪制3&#x…

精益數據分析(17/126):精益畫布與創業方向抉擇

精益數據分析&#xff08;17/126&#xff09;&#xff1a;精益畫布與創業方向抉擇 大家好&#xff01;一直以來&#xff0c;我都希望能和大家一起在創業和數據分析的領域中不斷探索、共同進步。今天&#xff0c;我們接著深入學習《精益數據分析》&#xff0c;這次聚焦于精益畫…

每天五分鐘深度學習PyTorch:圖像的處理的上采樣和下采樣

本文重點 在pytorch中封裝了上采樣和下采樣的方法,我們可以使用封裝好的方法可以很方便的完成采樣任務,采樣分為上采樣和下采樣。 上采樣和下采樣 下采樣(縮小圖像)的主要目的有兩個:1、使得圖像符合顯示區域的大小;2、生成對應圖像的縮略圖。 下采樣( 放大圖像)的…

代碼隨想錄訓練營第39天 || 198. 打家劫舍 213. 打家劫舍 II 337. 打家劫舍 III

198. 打家劫舍 思路&#xff1a; 動規五部曲&#xff1a; 1.dp數組及其下標的意義&#xff1a;dp數組表示當前房屋下偷與不偷的最大盜取金額 2.確定遞推公式&#xff1a;因為盜取房屋只能間隔盜取&#xff0c;并且還要取最大值。所以每個房屋都有盜取和不盜取兩個選擇&…

【AI 加持下的 Python 編程實戰 2_09】DIY 拓展:從掃雷小游戲開發再探問題分解與 AI 代碼調試能力(上)

DIY 拓展&#xff1a;從掃雷小游戲開發再探問題分解與 AI 代碼調試能力&#xff08;上&#xff09; 1 起因 最近在看去年剛出了第 2 版《Learn AI-assisted Python Programming》&#xff0c;梳理完 第七章 的知識點后&#xff0c;總感覺這一章的話題很好——問題分解能力的培…

使用DeepSeek-Prover-V1.5解決數學問題

DeepSeek-Prover-V1.5-RLRMaxTS是一個結合強化學習和搜索策略的自動定理證明系統。 1. 初等代數&#xff1a;二次方程求解 問題&#xff1a;解方程 x - 5x 6 0 操作步驟&#xff1a; 將問題轉換為Coq形式&#xff1a; Theorem quadratic : exists x : Z, x^2 - 5*x 6 0…

3.3 技術框架:LangChain、ReAct、Memory與Tool Integration

隨著人工智能技術的飛速發展&#xff0c;智能代理&#xff08;Agent&#xff09;已成為企業實現自動化、智能化和個性化服務的核心工具。在2025年&#xff0c;技術框架如LangChain、ReAct、Memory和Tool Integration在構建高效、靈活的AI代理系統中占據了重要地位。這些框架通過…

STM32F103 單片機(基于 ARM Cortex-M3 內核)的啟動過程涉及硬件初始化、固件配置和程序執行流程。

1. 啟動模式與地址映射 STM32F103 的啟動模式由 BOOT0 和 BOOT1 引腳配置決定&#xff0c;不同的啟動模式對應不同的存儲器映射&#xff1a; 啟動模式 映射地址范圍 說明 主 Flash 0x08000000~0x0807FFFF 用戶程序存儲在 Flash 中&#xff0c;復位后從 Flash 啟動&#xff08…

【C語言-選擇排序算法】實現對十個數進行排序

目錄 前言 一、選擇排序算法原理 二、選擇排序算法實現對十個數進行排序 三、代碼運行示例 四、選擇排序算法的時間復雜度和空間復雜度分析 五、選擇排序算法的優缺點 六、總結 前言 在計算機科學領域&#xff0c;排序算法是基石般的存在&#xff0c;它們就像是整理雜亂…

配置Intel Realsense D405驅動與ROS包

配置sdk使用 Ubuntu20.04LTS下安裝Intel Realsense D435i驅動與ROS包_realsense的驅動包-CSDN博客 中的方法一 之后不通過apt安裝包&#xff0c;使用官方的安裝步驟直接clone https://github.com/IntelRealSense/realsense-ros/tree/ros1-legacy 從這一步開始 執行完 這一步…

基于SpringBoot的中華詩詞文化分享平臺-項目分享

基于SpringBoot的中華詩詞文化分享平臺-項目分享 項目介紹項目摘要管理員功能圖會員功能圖系統功能圖項目預覽會員主頁面詩詞頁面發布問題回復評論 最后 項目介紹 使用者&#xff1a;管理員、會員 開發技術&#xff1a;MySQLJavaSpringBootVue 項目摘要 本文旨在設計與實現一…

ProxySQL 性能調優工具推薦

ProxySQL 的性能優化需結合?實時監控工具?與?自動化分析平臺?,以下為常用工具分類與推薦: 一、?內置診斷工具? ProxySQL Admin 接口? 通過內置管理表直接分析性能數據: sql Copy Code SELECT * FROM stats_mysql_query_digest; – 高頻查詢分析(執行次數、平均耗…

unity TEngine學習記錄3

上一篇講了怎么使用te框架&#xff0c;本篇主要學習的是UI&#xff0c;一個游戲百分之70%都是UI的展示效果&#xff0c;現在讓我們繼續打開te官網找到UI部分繼續學習。 ui創建以及加載 我們根據文檔首先打開命名規則界面,大家第一次看就知道這個是干啥的&#xff0c;你想使用此…

23種設計模式-創建型模式之單例模式(Java版本)

Java 單例模式&#xff08;Singleton Pattern&#xff09;詳解 &#x1f31f; 什么是單例模式&#xff1f; 單例模式確保一個類只有一個實例&#xff0c;并提供一個全局訪問點來訪問它。 &#x1f9e0; 使用場景 配置管理類&#xff08;如讀取配置文件&#xff09;日志工具類…

2025能源網絡安全大賽CTF --- Crypto wp

文章目錄 前言simpleSigninNumberTheory 前言 大半年以來寫的第一篇文章&#xff01;&#xff01;&#xff01; simpleSignin 題目&#xff1a; from Crypto.Util.number import * from gmpy2 import * import osflag bxxx p next_prime(bytes_to_long(os.urandom(128))…

加密與解密完全指南,使用Java實現

文章目錄 1. 加密基礎知識1.1 什么是加密&#xff1f;1.2 加密的歷史簡介1.2.1 古典加密1.2.2 現代加密的起源 1.3 加密的基本概念1.3.1 密碼學中的關鍵術語1.3.2 加密的基本原則 1.4 加密的分類1.4.1 對稱加密&#xff08;Symmetric Encryption&#xff09;1.4.2 非對稱加密&a…

十一、數據庫day03--SQL語句02

文章目錄 一、查詢語句1. 基本查詢2. 條件查詢2.1 ?較運算符&邏輯運算符2.2 模糊查詢2.3 范圍查詢2.4 判斷空 3. 其他復雜查詢3.1 排序3.2 聚合函數3.3 分組3.4 分頁查詢 二、回顧1. 使? Navicat ?具中的命令列2.命令?基本操作步驟 提示&#xff1a;以下是本篇文章正文…