From e644bfde0ea0c4644462c2eec131bcc17e4f5158 Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Tue, 9 Jan 2024 11:49:21 +0800 Subject: [PATCH] chore: add jdbc demo --- .../src/main/java/io/greptime/QueryJDBC.java | 54 ++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/ingester-example/src/main/java/io/greptime/QueryJDBC.java b/ingester-example/src/main/java/io/greptime/QueryJDBC.java index 1aadda2..04e1f01 100644 --- a/ingester-example/src/main/java/io/greptime/QueryJDBC.java +++ b/ingester-example/src/main/java/io/greptime/QueryJDBC.java @@ -15,26 +15,65 @@ */ package io.greptime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.Properties; +import java.util.concurrent.ExecutionException; /** * @author jiachun.fjc */ public class QueryJDBC { + private static final Logger LOG = LoggerFactory.getLogger(QueryJDBC.class); + public static void main(String[] args) throws Exception { GreptimeDB greptimeDB = TestConnector.connectToDefaultDB(); // Inserts data first - + insertData(greptimeDB); try (Connection conn = makeConnection()) { + Statement statement = conn.createStatement(); + + // DESC table; + ResultSet rs = statement.executeQuery("DESC cpu_metric"); + LOG.info("Column | Type | Key | Null | Default | Semantic Type "); + while (rs.next()) { + LOG.info("{} | {} | {} | {} | {} | {}", // + rs.getString(1), // + rs.getString(2), // + rs.getString(3), // + rs.getString(4), // + rs.getString(5), // + rs.getString(6)); + } + + // SELECT COUNT(*) FROM cpu_metric; + rs = statement.executeQuery("SELECT COUNT(*) FROM cpu_metric"); + while (rs.next()) { + LOG.info("Count: {}", rs.getInt(1)); + } + // SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5; + rs = statement.executeQuery("SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5"); + LOG.info("host | ts | cpu_user | cpu_sys"); + while (rs.next()) { + LOG.info("{} | {} | {} | {}", // + rs.getString("host"), // + rs.getTimestamp("ts"), // + rs.getDouble("cpu_user"), // + rs.getDouble("cpu_sys")); + } } } @@ -53,4 +92,17 @@ public static Connection makeConnection() throws IOException, ClassNotFoundExcep return Objects.requireNonNull(dbConn, "Failed to make connection!"); } + + public static void insertData(GreptimeDB greptimeDB) throws ExecutionException, InterruptedException { + List cpus = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + Cpu c = new Cpu(); + c.setHost("127.0.0." + i); + c.setTs(System.currentTimeMillis()); + c.setCpuUser(i + 0.1); + c.setCpuSys(i + 0.12); + cpus.add(c); + } + greptimeDB.writePOJOs(cpus).get(); + } }