因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;
? ? }
}
?