Skip to content

Commit

Permalink
chore: add jdbc demo
Browse files Browse the repository at this point in the history
  • Loading branch information
fengjiachun committed Jan 9, 2024
1 parent 2063fe6 commit e644bfd
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion ingester-example/src/main/java/io/greptime/QueryJDBC.java
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
}
}

Expand All @@ -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<Cpu> 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();
}
}

0 comments on commit e644bfd

Please sign in to comment.