|
@ -0,0 +1,76 @@ |
|
|
|
|
|
package com.bfd.clickhouse; |
|
|
|
|
|
|
|
|
|
|
|
import java.sql.*; |
|
|
|
|
|
|
|
|
|
|
|
public class TestClickhouse { |
|
|
|
|
|
|
|
|
|
|
|
public static void main(String[] args) { |
|
|
|
|
|
try { |
|
|
|
|
|
// 获取链接 |
|
|
|
|
|
Connection connection = getConnection(); |
|
|
|
|
|
// 创建表 |
|
|
|
|
|
createTable(connection); |
|
|
|
|
|
// // 插入数据 |
|
|
|
|
|
// insertData(connection); |
|
|
|
|
|
// 查询数据 |
|
|
|
|
|
// queryData(connection); |
|
|
|
|
|
} catch (Exception e) { |
|
|
|
|
|
e.printStackTrace(); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
private static void queryData(Connection connection) { |
|
|
|
|
|
try{ |
|
|
|
|
|
Statement statement = connection.createStatement(); |
|
|
|
|
|
|
|
|
|
|
|
String sql = "select age,count(*) from test.jdbc_example GROUP BY age"; |
|
|
|
|
|
ResultSet rs = statement.executeQuery(sql); |
|
|
|
|
|
|
|
|
|
|
|
while (rs.next()) { |
|
|
|
|
|
// ResultSet 的下标值从 1 开始,不可使用 0,否则越界,报 ArrayIndexOutOfBoundsException 异常 |
|
|
|
|
|
System.out.println(rs.getObject(1)+" : "+rs.getObject(2)); |
|
|
|
|
|
// System.out.println(rs.getDate(1) + ", " + rs.getString(2) + ", " + rs.getInt(3)); |
|
|
|
|
|
} |
|
|
|
|
|
}catch (Exception e){ |
|
|
|
|
|
e.printStackTrace(); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 插入数据 |
|
|
|
|
|
private static void insertData(Connection connection) { |
|
|
|
|
|
try{ |
|
|
|
|
|
PreparedStatement pstmt = connection.prepareStatement("insert into test.jdbc_example values(?, ?, ?)"); |
|
|
|
|
|
// insert 10 records |
|
|
|
|
|
for (int i = 0; i < 10; i++) { |
|
|
|
|
|
pstmt.setDate(1, new Date(System.currentTimeMillis())); |
|
|
|
|
|
pstmt.setString(2, "panda_" + (i + 1)); |
|
|
|
|
|
pstmt.setInt(3, 18); |
|
|
|
|
|
pstmt.addBatch(); |
|
|
|
|
|
} |
|
|
|
|
|
pstmt.executeBatch(); |
|
|
|
|
|
}catch (Exception e){ |
|
|
|
|
|
e.printStackTrace(); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
// 创建表 |
|
|
|
|
|
private static void createTable(Connection connection ) { |
|
|
|
|
|
try { |
|
|
|
|
|
Statement statement = connection.createStatement(); |
|
|
|
|
|
statement.executeQuery("create table test1.jdbc_example(day Date, name String, age UInt8) Engine=Log"); |
|
|
|
|
|
}catch (Exception e){ |
|
|
|
|
|
e.printStackTrace(); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
// 获取链接 |
|
|
|
|
|
private static Connection getConnection() { |
|
|
|
|
|
try { |
|
|
|
|
|
Class.forName("com.github.housepower.jdbc.ClickHouseDriver"); |
|
|
|
|
|
Connection connection = DriverManager.getConnection("jdbc:clickhouse://172.26.11.111:8123"); |
|
|
|
|
|
return connection; |
|
|
|
|
|
}catch (Exception e){ |
|
|
|
|
|
e.printStackTrace(); |
|
|
|
|
|
return null; |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
} |