当前位置: 首页 > java >正文

查询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.xdnf.cn/news/1397.html

相关文章:

  • php基础
  • 算法训练营第一天|704.二分查找、27.移除元素、977.有序数组的平方
  • 集结号海螺捕鱼组件搭建教程与源码结构详解(第四篇)
  • crictl 拉取镜像报错 Unimplemented desc = unknown service runtime.v1.ImageService
  • redis 使用 Docker 部署 简单的Redis 集群(包括哨兵机制)
  • 修电脑之电脑没有声音
  • 武装Burp Suite工具:xia SQL自动化测试_插件
  • date-picker组件的shortcuts为什么不能配置在vue的data的return中
  • 小红书文字配图平替工具
  • Vue3-原始值的响应式方案ref
  • 实时数仓体系概览与架构演进
  • python实战项目64:selenium采集软科中国大学排名数据
  • Django DRF实现用户数据权限控制
  • 服务器数据恢复—双循环RAID5数据恢复揭秘
  • 2025.04.23华为机考第二题-200分
  • 第七节:进阶特性高频题-Vue3的ref与reactive选择策略
  • 数据结构初阶:二叉树(四)
  • CSS3 基础(边框效果)
  • 从 Vue 到 React:React.memo + useCallback 组合技
  • PCB规则
  • 【android bluetooth 协议分析 11】【AVDTP详解 2】【avdtp 初始化阶段主要回调关系梳理】
  • 基于FPGA 和DSP 的高性能6U VPX 采集处理板
  • 深入解析C++ STL Queue:先进先出的数据结构
  • Android Gradle Plugin (AGP) 和 Gradle 的關係
  • 【Qwen2.5-VL 踩坑记录】本地 + 海外账号和国内账号的 API 调用区别(阿里云百炼平台)
  • 学习记录:DAY16
  • 2.RabbitMQ - 入门
  • 从入门到精通:CMakeLists.txt 完全指南
  • AI语音助手自定义角色百度大模型 【全新AI开发套件掌上AI+4w字教程+零基础上手】
  • 永磁同步电机控制算法-反馈线性化控制