查询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.mzph.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;以下是本篇文章正文…