clickhouse通过java jdbc实现增删改查,保姆级教程

一、clickhouse是一款开源的用于在线分析处理查询(OLAP :Online Analytical Processing)MPP架构的列式存储数据库。

二、clickhouse可以做用户行为分析,流批一体

三、我们现在用java通过jdbc的方式来操作clickhouse

四、先安装clickhouse,安装资料自行查找

五、操作步骤如下

5.1、在maven中引入clickhouse jar包

            <dependency>
				<groupId>com.clickhouse</groupId>
				<artifactId>clickhouse-jdbc</artifactId>
				<version>0.5.0</version>
			</dependency>
			<dependency>
				<groupId>com.clickhouse</groupId>
				<artifactId>clickhouse-client</artifactId>
				<version>0.5.0</version>
			</dependency>
			<dependency>
				<groupId>com.clickhouse</groupId>
				<artifactId>clickhouse-http-client</artifactId>
				<version>0.5.0</version>
			</dependency>

			<dependency>
				<groupId>org.apache.httpcomponents.client5</groupId>
				<artifactId>httpclient5</artifactId>
				<version>5.2.1</version>
			</dependency>
			<dependency>
				<groupId>org.apache.httpcomponents.client5</groupId>
				<artifactId>httpclient5-fluent</artifactId>
				<version>5.1.3</version>
			</dependency>

5.2、注意,httpclient5-fluent和httpclient5必须引入,否则会报错

5.3、编写一个DriverPropertyCreator 驱动接口

import java.sql.DriverPropertyInfo;
import java.util.Properties;

public interface DriverPropertyCreator {

	DriverPropertyInfo createDriverPropertyInfo(Properties properties);
}

5.4、编写一个ClickHouseQueryParam枚举


import java.sql.DriverPropertyInfo;
import java.util.Locale;
import java.util.Properties;

public enum ClickHouseQueryParam implements DriverPropertyCreator {

	DATABASE("database", null, String.class, "database name used by default"),
	USER("user", null, String.class, "user name, by default - default"),
	PASSWORD("password", null, String.class, "user password, by default null");

	private final String key;
	private final Object defaultValue;
	private final Class<?> clazz;
	private final String description;

	<T> ClickHouseQueryParam(String key, T defaultValue, Class<T> clazz, String description) {
		this.key = key;
		this.defaultValue = defaultValue;
		this.clazz = clazz;
		this.description = description;
	}

	public String getKey() {
		return key;
	}

	public Object getDefaultValue() {
		return defaultValue;
	}

	public Class<?> getClazz() {
		return clazz;
	}

	public String getDescription() {
		return description;
	}

	@Override
	public String toString() {
		return name().toLowerCase(Locale.ROOT);
	}

	@Override
	public DriverPropertyInfo createDriverPropertyInfo(Properties properties) {
		DriverPropertyInfo propertyInfo = new DriverPropertyInfo(key, driverPropertyValue(properties));
		propertyInfo.required = false;
		propertyInfo.description = description;
		propertyInfo.choices = driverPropertyInfoChoices();
		return propertyInfo;
	}

	private String[] driverPropertyInfoChoices() {
		return clazz == Boolean.class || clazz == Boolean.TYPE ? new String[] { "true", "false" } : null;
	}

	private String driverPropertyValue(Properties properties) {
		String value = properties.getProperty(key);
		if (value == null) {
			value = defaultValue == null ? null : defaultValue.toString();
		}
		return value;
	}
}

5.5、编写一个ClickHouseConnectionSettings枚举


import java.sql.DriverPropertyInfo;
import java.util.Properties;

public enum ClickHouseConnectionSettings implements DriverPropertyCreator {

	SOCKET_TIMEOUT("socket_timeout", 30000, "");

	private final String key;
	private final Object defaultValue;
	private final String description;
	private final Class<?> clazz;

	ClickHouseConnectionSettings(String key, Object defaultValue, String description) {
		this.key = key;
		this.defaultValue = defaultValue;
		this.clazz = defaultValue.getClass();
		this.description = description;
	}

	public String getKey() {
		return key;
	}

	public Object getDefaultValue() {
		return defaultValue;
	}

	public Class<?> getClazz() {
		return clazz;
	}

	public String getDescription() {
		return description;
	}

	public DriverPropertyInfo createDriverPropertyInfo(Properties properties) {
		DriverPropertyInfo propertyInfo = new DriverPropertyInfo(key, driverPropertyValue(properties));
		propertyInfo.required = false;
		propertyInfo.description = description;
		propertyInfo.choices = driverPropertyInfoChoices();
		return propertyInfo;
	}

	private String[] driverPropertyInfoChoices() {
		return clazz == Boolean.class || clazz == Boolean.TYPE ? new String[] { "true", "false" } : null;
	}

	private String driverPropertyValue(Properties properties) {
		String value = properties.getProperty(key);
		if (value == null) {
			value = defaultValue == null ? null : defaultValue.toString();
		}
		return value;
	}
}

5.6、编写一个ClickHouseProperties类


import java.util.Properties;

public class ClickHouseProperties {

	private String user;
	private String password;
	private String database;
	private int socketTimeout;

	public ClickHouseProperties() {
		this(new Properties());
	}

	public ClickHouseProperties(Properties info) {
		this.socketTimeout = (Integer) getSetting(info, ClickHouseConnectionSettings.SOCKET_TIMEOUT);

		this.database = getSetting(info, ClickHouseQueryParam.DATABASE);

		this.user = getSetting(info, ClickHouseQueryParam.USER);
		this.password = getSetting(info, ClickHouseQueryParam.PASSWORD);
	}

	public Properties asProperties() {
		PropertiesBuilder ret = new PropertiesBuilder();
		ret.put(ClickHouseConnectionSettings.SOCKET_TIMEOUT.getKey(), String.valueOf(socketTimeout));
		ret.put(ClickHouseQueryParam.USER.getKey(), user);
		ret.put(ClickHouseQueryParam.PASSWORD.getKey(), password);
		ret.put(ClickHouseQueryParam.DATABASE.getKey(), database);
		return ret.getProperties();
	}

	public ClickHouseProperties(ClickHouseProperties properties) {
		setUser(properties.user);
		setPassword(properties.password);
		setDatabase(properties.database);
		setSocketTimeout(properties.socketTimeout);
	}

	private <T> T getSetting(Properties info, ClickHouseQueryParam param) {
		return getSetting(info, param.getKey(), param.getDefaultValue(), param.getClazz());
	}

	private <T> T getSetting(Properties info, ClickHouseConnectionSettings settings) {
		return getSetting(info, settings.getKey(), settings.getDefaultValue(), settings.getClazz());
	}

	@SuppressWarnings("unchecked")
	private <T> T getSetting(Properties info, String key, Object defaultValue, Class<?> clazz) {
		String val = info.getProperty(key);
		if (val == null) {
			return (T) defaultValue;
		}
		if (clazz == int.class || clazz == Integer.class) {
			return (T) clazz.cast(Integer.valueOf(val));
		}
		if (clazz == long.class || clazz == Long.class) {
			return (T) clazz.cast(Long.valueOf(val));
		}
		if (clazz == boolean.class || clazz == Boolean.class) {
			final Boolean boolValue;
			if ("1".equals(val) || "0".equals(val)) {
				boolValue = "1".equals(val);
			} else {
				boolValue = Boolean.valueOf(val);
			}
			return (T) clazz.cast(boolValue);
		}
		return (T) clazz.cast(val);
	}

	public int getSocketTimeout() {
		return socketTimeout;
	}

	public void setSocketTimeout(int socketTimeout) {
		this.socketTimeout = socketTimeout;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getDatabase() {
		return database;
	}

	public void setDatabase(String database) {
		this.database = database;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	private static class PropertiesBuilder {
		private final Properties properties;

		public PropertiesBuilder() {
			properties = new Properties();
		}

		public void put(String key, String value) {
			if (value != null) {
				properties.put(key, value);
			}
		}

		public Properties getProperties() {
			return properties;
		}
	}
}

5.7、开始编写jdbc操作clickhouse的ClickhouseDemo


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.demoflowable.common.ClickHouseProperties;

import com.clickhouse.jdbc.ClickHouseConnection;
import com.clickhouse.jdbc.ClickHouseDataSource;


public class ClickhouseDemo {

	private static String username = "default";
	private static String password = "123456";
	private static String address = "jdbc:clickhouse://192.168.42.142:8123";
	private static String db = "bigdata";
	private static int socketTimeout = 600000;

	public static void main(String[] args) throws Exception {
		getConnection();
		dropTable();
		createTable(
				"create table t_demo_02(id UInt32,sku String,amount Decimal(16,2),create_time Datetime) engine =MergeTree partition by toYYYYMMDD(create_time) primary key (id) order by (id,sku);");
		insertDemo();
		queryDemo();
		updateDemoById();
		deleteDemoById();
	}

	/**
	 * 查询数据
	 */
	public static void queryDemo() {
		List<Map<String, Object>> list = new ArrayList<>();
		String sql = "select * from t_demo";
		Connection connection = getConnection();
		try {
			Statement statement = connection.createStatement();
			ResultSet rs = statement.executeQuery(sql);
			ResultSetMetaData rsmd = rs.getMetaData();
			while (rs.next()) {
				Map<String, Object> row = new HashMap<>();
				for (int i = 1; i <= rsmd.getColumnCount(); i++) {
					row.put(rsmd.getColumnName(i), rs.getObject(rsmd.getColumnName(i)));
				}
				list.add(row);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		list.stream().forEach(item -> {
			Map<String, Object> rowData = item;
			System.out.println(rowData);
		});
		close(connection);
	}

	/**
	 * 创建表
	 * 
	 * @throws Exception
	 */
	public static void createTable(String tableSql) throws Exception {
		Connection connection = null;
		try {
			connection = getConnection();
			Statement statement = connection.createStatement();
			boolean execute = statement.execute(tableSql);
			if (execute) {
				System.out.println("创建表成功," + execute);
			}
		} finally {
			close(connection);
		}
	}

	/**
	 * 删除表
	 * 
	 * @throws Exception
	 */
	public static void dropTable() throws Exception {
		Connection connection = null;
		try {
			connection = getConnection();
			Statement statement = connection.createStatement();
			statement.execute("drop table t_demo_02;");
			System.out.println("删除表成功");
		} finally {
			close(connection);
		}
	}

	/**
	 * 
	 * @throws Exception
	 */
	public static void insertDemo() throws Exception {
		Connection connection = null;
		try {
			connection = getConnection();
			for (int i = 0; i < 5; i++) {
				String id = "10" + i;
				String sku = "sku20231108" + i;
				PreparedStatement pstmt = connection.prepareStatement(
						"insert into t_demo values(" + id + ", '" + sku + "', '6500.00','2023-11-08 12:00:00')");
				pstmt.execute();
			}
			System.out.println("insert success");
		} finally {
			close(connection);
		}
	}

	/**
	 */
	public static void deleteDemoById() throws Exception {
		Connection connection = null;
		try {
			connection = getConnection();
			PreparedStatement pstmt = connection.prepareStatement("delete from t_demo where sku = 'sku2023110801';");
			pstmt.execute();
			System.out.println("delete success");
		} finally {
			close(connection);
		}
	}

	/**
	 */
	public static void updateDemoById() throws Exception {
		Connection connection = null;
		try {
			connection = getConnection();
			PreparedStatement pstmt = connection
					.prepareStatement("alter table t_demo update amount=toDecimal32(1200.00,3) where id = '101'");
			pstmt.execute();
			System.out.println("update success");
		} finally {
			close(connection);
		}
	}

	public static Connection getConnection() {
		ClickHouseProperties properties = new ClickHouseProperties();
		properties.setUser(username);
		properties.setPassword(password);
		properties.setDatabase(db);
		properties.setSocketTimeout(socketTimeout);
		try {
			ClickHouseDataSource clickHouseDataSource = new ClickHouseDataSource(address, properties.asProperties());
			ClickHouseConnection conn = clickHouseDataSource.getConnection();
			System.out.println("连接成功");
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void close(Connection connection) {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
}

整个过程就是这样,完全保姆级教程。操作后的效果,如下

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/122418.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

通达OA V12版,引入thinkphp5.1框架,及获取session

通达OA V12版&#xff0c;引入thinkphp5.1框架 如下过程引入如下问题&#xff0c;按上述问题解决htmlentities(): charset cp936 not supported, assuming utf-8 内容绝对原创&#xff0c;希望对您有帮助。您的打赏&#xff0c;是让我持续更新的牛奶和面包 如下过程引入 在D:/…

有效降低数据库存储成本方案与实践 | 京东云技术团队

背景 随着平台的不断壮大&#xff0c;业务的不断发展&#xff0c;后端系统的数据量、存储所使用的硬件成本也逐年递增。从发展的眼光看&#xff0c;业务与系统要想健康的发展&#xff0c;成本增加的问题必须重视起来。目前业界普遍认同开源节流大方向&#xff0c;很多企业部门…

总结Kibana DevTools如何操作elasticsearch的常用语句

一、操作es的工具 ElasticSearch HeadKibana DevToolsElasticHQ 本文主要是总结Kibana DevTools操作es的语句。 二、搜索文档 1、根据ID查询单个记录 GET /course_idx/_doc/course:202、term 匹配"name"字段的值为"6789999"的文档 类似于sql语句中的等…

载波通讯电表的使用年限是多久?

随着科技的飞速发展&#xff0c;智能家居、物联网等概念逐渐深入人心&#xff0c;载波通讯电表作为一种新型的智能电表&#xff0c;凭借其低功耗、高可靠性、远程通讯等优点&#xff0c;广泛应用于居民用电、工业生产等领域。那么&#xff0c;载波通讯电表的使用年限是多久呢&a…

vTESTstudio的使用

vTESTstudio介绍 vTESTstudio是Vector公司专为ECU自动化测试而研发的测试用例编写软件&#xff0c;可用于从模型测试到系统确认的所有开发阶段。它集成了多种用例编辑方法&#xff0c;能有效提高测试人员对测试设计的效率、具有可复用性等优点。它支持Python作为测试编程语言&…

vtk夹角计算控件

开发环境&#xff1a; Windows 11 家庭中文版Microsoft Visual Studio Community 2019VTK-9.3.0.rc0vtk-example参考代码目的&#xff1a;学习与总结 demo解决问题&#xff1a;renderWindow中创建一个夹角测量控件&#xff0c;通过三个点确定一个夹角 典型的控件类继承关系&am…

第134届广交会圆满落幕,百华鞋业不负众望,载誉收官!

第134届广交会线下展在广州圆满落幕&#xff0c;交出了亮眼的成绩单。相比往届&#xff0c;本届广交会展览总面积扩至155万平方米&#xff0c;展位总数7.4万个&#xff0c;展区总数55个&#xff0c;参展企业28533家&#xff0c;均创历史新高。据央媒等相关报道&#xff0c;本届…

Ubuntu LTS 坚持 10 年更新不动摇

导读Linux 内核开发者 Jonathan Corbet 此前在欧洲开源峰会上宣布&#xff0c;LTS 内核的支持时间将从六年缩短至两年&#xff0c;原因在于缺乏使用和缺乏支持。稳定版内核维护者 Greg Kroah-Hartman 也表示 “没人用 LTS 内核”。 近日&#xff0c;Ubuntu 开发商 Canonical 发…

COOHOM通过采用亚马逊云科“专库专用”的方式,为云原生的构建提供稳定的数据支撑

全球化浪潮下&#xff0c;面对全球化业务发展带来的新需求与新挑战&#xff0c;越来越多的企业开启了云原生构建旅程&#xff0c;以推动业务系统快速迭代&#xff0c;为国际业务的拓展打下坚实的基础。COOHOM是杭州群核信息技术有限公司旗下的国际化品牌。为全球企业和个人提供…

taro(踩坑) npm run dev:weapp 微信小程序开发者工具预览报错

控制台报错信息&#xff1a; VM72:9 app.js错误: Error: module vendors-node_modules_taro_weapp_prebundle_chunk-JUEIR267_js.js is not defined, require args is ./vendors-node_modules_taro_weapp_prebundle_chunk-JUEIR267_js.js 环境&#xff1a; node 版本&#x…

KubeSphere v3.4.0 部署K8S Docker + Prometheus + grafana

KubeSphere v3.4.0 部署K8S 1、整体思路2、修改linux主机名3、 离线安装3.1 问题列表3.2 执行命令成功列表 1、整体思路 将KubeSphere v3.4.0 安装包传输到其中一台机器修改Linux主机名&#xff08;选取3台&#xff0c;修改为master01、master02、master03&#xff09;安装官方…

电脑监控软件怎样防止数据泄露丨实战干货分享

电脑监控软件大家应该都不陌生吧&#xff0c;原本它是国外的产物&#xff0c;只不过在02年的时候&#xff0c;在国内出现。 一开始它的功能也仅限于监控应该的电脑画面&#xff0c;但是随着电脑问题逐渐增加&#xff0c;其他和公司企业管理、员工管理、防止数据泄露的功能就都…

仿mudou库one thread one loop式并发服务器

目录 1.实现目标 2.HTTP服务器 实现高性能服务器-Reactor模型 模块划分 SERVER模块&#xff1a; HTTP协议模块&#xff1a; 3.项目中的子功能 秒级定时任务实现 时间轮实现 正则库的简单使用 通⽤类型any类型的实现 4.SERVER服务器实现 日志宏的封装 缓冲区Buffer…

vscode中 vue3+ts 项目的提示失效,volar插件失效问题解决方案

文章目录 前情提要bug回顾解决方案最后 前情提要 说起来很耻辱&#xff0c;从mac环境换到window环境&#xff0c;vscode的配置都是云端更新过来的&#xff0c;应该是一切正常才对&#xff0c;奇怪的是我的项目环境出现问题了&#xff0c;关于组件的ts和追踪都没有效果&#xff…

IDEA版SSM入门到实战(Maven+MyBatis+Spring+SpringMVC) -Maven核心概念

一.Maven的POM POM全称&#xff1a;Project Object Model【项目对象模型】&#xff0c;将项目封装为对象模型&#xff0c;便于使用Maven管理【构建】项目 pom.xml常用标签 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://m…

C#中.NET 7.0控制台应用使用LINQtoSQL、LINQtoXML

目录 一、新建控制台应用和数据库连接 二、手动添加System.Data.Linq程序包 三、手动添加System.Data.SqlClient程序包 四、再次操作DataClasses1.dbml 五、示例 1.源码 2.xml文件 默认安装的.NET 7.0控制台应用是不支持使用LINQtoSQL、LINQtoXML的。 默认安装的.NET F…

基于springboot实现高校党务平台管理系统【项目源码】计算机毕业设计

基于springboot实现高校党务平台管理系统演示 Java技术 Java是由Sun公司推出的一门跨平台的面向对象的程序设计语言。因为Java 技术具有卓越的通用性、高效性、健壮的安全性和平台移植性的特点&#xff0c;而且Java是开源的&#xff0c;拥有全世界最大的开发者专业社群&#x…

提升绘图效率不再难,看看这8款AI流程图软件,一键快速生成流程图!

流程图是表示流程、系统和思想的重要视觉辅助工具。在当今数字时代&#xff0c;AI技术的出现已经彻底改变了制作流程图的方式。 在本文中&#xff0c;我们将与各位分享8款好用的AI流程图软件&#xff0c;借助每款软件内置的AI能力&#xff0c;可以快速绘制出一份完整的流程图&…

物联网中的毫米波雷达:连接未来的智能设备

随着物联网&#xff08;IoT&#xff09;技术的飞速发展&#xff0c;连接设备的方式和效能变得越来越重要。毫米波雷达技术作为一种先进的感知技术&#xff0c;正在为物联网设备的连接和智能化提供全新的可能性。本文将深入探讨毫米波雷达在物联网中的应用&#xff0c;以及它是如…

城市内涝积水预防,万宾科技内涝监测仪如何预警?

近几年来城市内涝所引发的安全隐患极为突出&#xff0c;影响着城市道路安全&#xff0c;而且也让市民心中多有惶恐。一旦城市内涝问题出现背后不仅是路面积水问题&#xff0c;更会导致城市无法正常运行&#xff0c;导致市民日常生活和工作受到影响。所以对于排水防涝设施的建设…