java操作Apache druid的实例代码

时间:2021-05-19

1. 添加maven依赖包

<dependency> <groupId>org.apache.calcite.avatica</groupId> <artifactId>avatica-core</artifactId> <version>1.15.0</version></dependency>

2. 编写工具类

package com.hnu.druid;import org.apache.calcite.avatica.AvaticaConnection;import org.apache.calcite.avatica.AvaticaStatement;import org.springframework.stereotype.Component;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import java.util.Properties;/** * @description: * @author: YUANHX * @create: 7:11 下午 **/@Componentpublic class DruidJdbcUtil { private static ThreadLocal<AvaticaConnection> threadLocal = new ThreadLocal<>(); private static final String DRUID_URL = "jdbc:avatica:remote:url=http://172.16.0.160:8888/druid/v2/sql/avatica/"; /** * 打开连接 * @param * @return * @throws SQLException */ public static AvaticaConnection connection() throws SQLException { Properties properties = new Properties(); AvaticaConnection connection = (AvaticaConnection) DriverManager.getConnection(DRUID_URL, properties); threadLocal.set(connection); return connection; } /** * 关闭连接 * @throws SQLException */ public static void closeConnection() throws SQLException{ System.out.println("关闭线程:"+threadLocal.get()); AvaticaConnection conn = threadLocal.get(); if(conn != null){ conn.close(); threadLocal.remove(); } } /** * 根据sql查询结果 * @param * @param sql * @return * @throws SQLException */ public static ResultSet executeQuery (String sql) throws SQLException{ AvaticaStatement statement = connection().createStatement(); ResultSet resultSet = statement.executeQuery(sql); return resultSet; } public static void main(String[] args) { try { String sql = "SELECT * FROM \"vehicleCondition\" limit 20"; for (int i = 0; i < 5; i++) { ResultSet resultSet = executeQuery(sql); System.out.println("开始连接"+i + "; 连接线程:"+threadLocal.get()); while(resultSet.next()){ String equipmentCode = resultSet.getString("EquipmentCode"); String vkaCode = resultSet.getString("VKACode");// System.out.println(equipmentCode + " ; "+ vkaCode); } closeConnection(); } } catch (SQLException throwables) { throwables.printStackTrace(); } }}

到此这篇关于java操作Apache druid的实例代码的文章就介绍到这了,更多相关java操作Apache druid内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章