当前位置:   article > 正文

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

clickhouse java

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

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

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

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

五、操作步骤如下

5.1、在maven中引入clickhouse jar包

  1. <dependency>
  2. <groupId>com.clickhouse</groupId>
  3. <artifactId>clickhouse-jdbc</artifactId>
  4. <version>0.5.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.clickhouse</groupId>
  8. <artifactId>clickhouse-client</artifactId>
  9. <version>0.5.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.clickhouse</groupId>
  13. <artifactId>clickhouse-http-client</artifactId>
  14. <version>0.5.0</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.httpcomponents.client5</groupId>
  18. <artifactId>httpclient5</artifactId>
  19. <version>5.2.1</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.apache.httpcomponents.client5</groupId>
  23. <artifactId>httpclient5-fluent</artifactId>
  24. <version>5.1.3</version>
  25. </dependency>

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

5.3、编写一个DriverPropertyCreator 驱动接口

  1. import java.sql.DriverPropertyInfo;
  2. import java.util.Properties;
  3. public interface DriverPropertyCreator {
  4. DriverPropertyInfo createDriverPropertyInfo(Properties properties);
  5. }

5.4、编写一个ClickHouseQueryParam枚举

  1. import java.sql.DriverPropertyInfo;
  2. import java.util.Locale;
  3. import java.util.Properties;
  4. public enum ClickHouseQueryParam implements DriverPropertyCreator {
  5. DATABASE("database", null, String.class, "database name used by default"),
  6. USER("user", null, String.class, "user name, by default - default"),
  7. PASSWORD("password", null, String.class, "user password, by default null");
  8. private final String key;
  9. private final Object defaultValue;
  10. private final Class<?> clazz;
  11. private final String description;
  12. <T> ClickHouseQueryParam(String key, T defaultValue, Class<T> clazz, String description) {
  13. this.key = key;
  14. this.defaultValue = defaultValue;
  15. this.clazz = clazz;
  16. this.description = description;
  17. }
  18. public String getKey() {
  19. return key;
  20. }
  21. public Object getDefaultValue() {
  22. return defaultValue;
  23. }
  24. public Class<?> getClazz() {
  25. return clazz;
  26. }
  27. public String getDescription() {
  28. return description;
  29. }
  30. @Override
  31. public String toString() {
  32. return name().toLowerCase(Locale.ROOT);
  33. }
  34. @Override
  35. public DriverPropertyInfo createDriverPropertyInfo(Properties properties) {
  36. DriverPropertyInfo propertyInfo = new DriverPropertyInfo(key, driverPropertyValue(properties));
  37. propertyInfo.required = false;
  38. propertyInfo.description = description;
  39. propertyInfo.choices = driverPropertyInfoChoices();
  40. return propertyInfo;
  41. }
  42. private String[] driverPropertyInfoChoices() {
  43. return clazz == Boolean.class || clazz == Boolean.TYPE ? new String[] { "true", "false" } : null;
  44. }
  45. private String driverPropertyValue(Properties properties) {
  46. String value = properties.getProperty(key);
  47. if (value == null) {
  48. value = defaultValue == null ? null : defaultValue.toString();
  49. }
  50. return value;
  51. }
  52. }

5.5、编写一个ClickHouseConnectionSettings枚举

  1. import java.sql.DriverPropertyInfo;
  2. import java.util.Properties;
  3. public enum ClickHouseConnectionSettings implements DriverPropertyCreator {
  4. SOCKET_TIMEOUT("socket_timeout", 30000, "");
  5. private final String key;
  6. private final Object defaultValue;
  7. private final String description;
  8. private final Class<?> clazz;
  9. ClickHouseConnectionSettings(String key, Object defaultValue, String description) {
  10. this.key = key;
  11. this.defaultValue = defaultValue;
  12. this.clazz = defaultValue.getClass();
  13. this.description = description;
  14. }
  15. public String getKey() {
  16. return key;
  17. }
  18. public Object getDefaultValue() {
  19. return defaultValue;
  20. }
  21. public Class<?> getClazz() {
  22. return clazz;
  23. }
  24. public String getDescription() {
  25. return description;
  26. }
  27. public DriverPropertyInfo createDriverPropertyInfo(Properties properties) {
  28. DriverPropertyInfo propertyInfo = new DriverPropertyInfo(key, driverPropertyValue(properties));
  29. propertyInfo.required = false;
  30. propertyInfo.description = description;
  31. propertyInfo.choices = driverPropertyInfoChoices();
  32. return propertyInfo;
  33. }
  34. private String[] driverPropertyInfoChoices() {
  35. return clazz == Boolean.class || clazz == Boolean.TYPE ? new String[] { "true", "false" } : null;
  36. }
  37. private String driverPropertyValue(Properties properties) {
  38. String value = properties.getProperty(key);
  39. if (value == null) {
  40. value = defaultValue == null ? null : defaultValue.toString();
  41. }
  42. return value;
  43. }
  44. }

5.6、编写一个ClickHouseProperties类

  1. import java.util.Properties;
  2. public class ClickHouseProperties {
  3. private String user;
  4. private String password;
  5. private String database;
  6. private int socketTimeout;
  7. public ClickHouseProperties() {
  8. this(new Properties());
  9. }
  10. public ClickHouseProperties(Properties info) {
  11. this.socketTimeout = (Integer) getSetting(info, ClickHouseConnectionSettings.SOCKET_TIMEOUT);
  12. this.database = getSetting(info, ClickHouseQueryParam.DATABASE);
  13. this.user = getSetting(info, ClickHouseQueryParam.USER);
  14. this.password = getSetting(info, ClickHouseQueryParam.PASSWORD);
  15. }
  16. public Properties asProperties() {
  17. PropertiesBuilder ret = new PropertiesBuilder();
  18. ret.put(ClickHouseConnectionSettings.SOCKET_TIMEOUT.getKey(), String.valueOf(socketTimeout));
  19. ret.put(ClickHouseQueryParam.USER.getKey(), user);
  20. ret.put(ClickHouseQueryParam.PASSWORD.getKey(), password);
  21. ret.put(ClickHouseQueryParam.DATABASE.getKey(), database);
  22. return ret.getProperties();
  23. }
  24. public ClickHouseProperties(ClickHouseProperties properties) {
  25. setUser(properties.user);
  26. setPassword(properties.password);
  27. setDatabase(properties.database);
  28. setSocketTimeout(properties.socketTimeout);
  29. }
  30. private <T> T getSetting(Properties info, ClickHouseQueryParam param) {
  31. return getSetting(info, param.getKey(), param.getDefaultValue(), param.getClazz());
  32. }
  33. private <T> T getSetting(Properties info, ClickHouseConnectionSettings settings) {
  34. return getSetting(info, settings.getKey(), settings.getDefaultValue(), settings.getClazz());
  35. }
  36. @SuppressWarnings("unchecked")
  37. private <T> T getSetting(Properties info, String key, Object defaultValue, Class<?> clazz) {
  38. String val = info.getProperty(key);
  39. if (val == null) {
  40. return (T) defaultValue;
  41. }
  42. if (clazz == int.class || clazz == Integer.class) {
  43. return (T) clazz.cast(Integer.valueOf(val));
  44. }
  45. if (clazz == long.class || clazz == Long.class) {
  46. return (T) clazz.cast(Long.valueOf(val));
  47. }
  48. if (clazz == boolean.class || clazz == Boolean.class) {
  49. final Boolean boolValue;
  50. if ("1".equals(val) || "0".equals(val)) {
  51. boolValue = "1".equals(val);
  52. } else {
  53. boolValue = Boolean.valueOf(val);
  54. }
  55. return (T) clazz.cast(boolValue);
  56. }
  57. return (T) clazz.cast(val);
  58. }
  59. public int getSocketTimeout() {
  60. return socketTimeout;
  61. }
  62. public void setSocketTimeout(int socketTimeout) {
  63. this.socketTimeout = socketTimeout;
  64. }
  65. public String getUser() {
  66. return user;
  67. }
  68. public void setUser(String user) {
  69. this.user = user;
  70. }
  71. public String getDatabase() {
  72. return database;
  73. }
  74. public void setDatabase(String database) {
  75. this.database = database;
  76. }
  77. public String getPassword() {
  78. return password;
  79. }
  80. public void setPassword(String password) {
  81. this.password = password;
  82. }
  83. private static class PropertiesBuilder {
  84. private final Properties properties;
  85. public PropertiesBuilder() {
  86. properties = new Properties();
  87. }
  88. public void put(String key, String value) {
  89. if (value != null) {
  90. properties.put(key, value);
  91. }
  92. }
  93. public Properties getProperties() {
  94. return properties;
  95. }
  96. }
  97. }

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

  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.ResultSetMetaData;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import org.demoflowable.common.ClickHouseProperties;
  12. import com.clickhouse.jdbc.ClickHouseConnection;
  13. import com.clickhouse.jdbc.ClickHouseDataSource;
  14. public class ClickhouseDemo {
  15. private static String username = "default";
  16. private static String password = "123456";
  17. private static String address = "jdbc:clickhouse://192.168.42.142:8123";
  18. private static String db = "bigdata";
  19. private static int socketTimeout = 600000;
  20. public static void main(String[] args) throws Exception {
  21. getConnection();
  22. dropTable();
  23. createTable(
  24. "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);");
  25. insertDemo();
  26. queryDemo();
  27. updateDemoById();
  28. deleteDemoById();
  29. }
  30. /**
  31. * 查询数据
  32. */
  33. public static void queryDemo() {
  34. List<Map<String, Object>> list = new ArrayList<>();
  35. String sql = "select * from t_demo";
  36. Connection connection = getConnection();
  37. try {
  38. Statement statement = connection.createStatement();
  39. ResultSet rs = statement.executeQuery(sql);
  40. ResultSetMetaData rsmd = rs.getMetaData();
  41. while (rs.next()) {
  42. Map<String, Object> row = new HashMap<>();
  43. for (int i = 1; i <= rsmd.getColumnCount(); i++) {
  44. row.put(rsmd.getColumnName(i), rs.getObject(rsmd.getColumnName(i)));
  45. }
  46. list.add(row);
  47. }
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. }
  51. list.stream().forEach(item -> {
  52. Map<String, Object> rowData = item;
  53. System.out.println(rowData);
  54. });
  55. close(connection);
  56. }
  57. /**
  58. * 创建表
  59. *
  60. * @throws Exception
  61. */
  62. public static void createTable(String tableSql) throws Exception {
  63. Connection connection = null;
  64. try {
  65. connection = getConnection();
  66. Statement statement = connection.createStatement();
  67. boolean execute = statement.execute(tableSql);
  68. if (execute) {
  69. System.out.println("创建表成功," + execute);
  70. }
  71. } finally {
  72. close(connection);
  73. }
  74. }
  75. /**
  76. * 删除表
  77. *
  78. * @throws Exception
  79. */
  80. public static void dropTable() throws Exception {
  81. Connection connection = null;
  82. try {
  83. connection = getConnection();
  84. Statement statement = connection.createStatement();
  85. statement.execute("drop table t_demo_02;");
  86. System.out.println("删除表成功");
  87. } finally {
  88. close(connection);
  89. }
  90. }
  91. /**
  92. *
  93. * @throws Exception
  94. */
  95. public static void insertDemo() throws Exception {
  96. Connection connection = null;
  97. try {
  98. connection = getConnection();
  99. for (int i = 0; i < 5; i++) {
  100. String id = "10" + i;
  101. String sku = "sku20231108" + i;
  102. PreparedStatement pstmt = connection.prepareStatement(
  103. "insert into t_demo values(" + id + ", '" + sku + "', '6500.00','2023-11-08 12:00:00')");
  104. pstmt.execute();
  105. }
  106. System.out.println("insert success");
  107. } finally {
  108. close(connection);
  109. }
  110. }
  111. /**
  112. */
  113. public static void deleteDemoById() throws Exception {
  114. Connection connection = null;
  115. try {
  116. connection = getConnection();
  117. PreparedStatement pstmt = connection.prepareStatement("delete from t_demo where sku = 'sku2023110801';");
  118. pstmt.execute();
  119. System.out.println("delete success");
  120. } finally {
  121. close(connection);
  122. }
  123. }
  124. /**
  125. */
  126. public static void updateDemoById() throws Exception {
  127. Connection connection = null;
  128. try {
  129. connection = getConnection();
  130. PreparedStatement pstmt = connection
  131. .prepareStatement("alter table t_demo update amount=toDecimal32(1200.00,3) where id = '101'");
  132. pstmt.execute();
  133. System.out.println("update success");
  134. } finally {
  135. close(connection);
  136. }
  137. }
  138. public static Connection getConnection() {
  139. ClickHouseProperties properties = new ClickHouseProperties();
  140. properties.setUser(username);
  141. properties.setPassword(password);
  142. properties.setDatabase(db);
  143. properties.setSocketTimeout(socketTimeout);
  144. try {
  145. ClickHouseDataSource clickHouseDataSource = new ClickHouseDataSource(address, properties.asProperties());
  146. ClickHouseConnection conn = clickHouseDataSource.getConnection();
  147. System.out.println("连接成功");
  148. return conn;
  149. } catch (SQLException e) {
  150. e.printStackTrace();
  151. }
  152. return null;
  153. }
  154. public static void close(Connection connection) {
  155. try {
  156. if (connection != null) {
  157. connection.close();
  158. }
  159. } catch (SQLException e) {
  160. e.printStackTrace();
  161. }
  162. }
  163. }

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/784648
推荐阅读
相关标签
  

闽ICP备14008679号