JDBC driver

Lenses offers a JDBC 4.0 compliant driver, suitable for any application that uses the JDBC interface, to communicate with Apache Kafka.

As with most JDBC drivers, it must be registered with the DriverManager before it can be used. The DriverManager is a singleton class which manages all known drivers and exposes them through the JDBC API. To register the Lenses’ driver, create an instance of the driver class, like so:

new io.lenses.jdbc4.LensesDriver()

You only need to place this in one place. It is typically located somewhere that it gets executed early in your application’s lifecycle.

Once the driver is registered, a connection to the Lenses server can be established, like so:

Connection conn = DriverManager.getConnection(
     "jdbc:lenses:kafka:http://localhost:3030",
     "username",
     "password");

With an opened connection, next a Statement instance can be created.

Statement stmt = conn.createStatement();

Next, using executeQuery(String) method sends a query to the Lenses platform and return the matching records as JDBC rows.

ResultSet rs = stmt.executeQuery( "SELECT * FROM mytopic");

When a statement executes a query, it returns a ResultSet instance, which acts as an iterator for the results. The result set has an internal cursor which points to the current row. A result set can be traversed by invoking the next() method. If there are no more records it will return false; otherwise the cursor is moved to the new row and its column values can be returned.

Connection conn = DriverManager.getConnection(
     "jdbc:lenses:kafka:http://localhost:3030",
     "username",
     "password");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM mytopic");

while (rs.next()) {
    System.out.println(rs.getString("name"));
    System.out.println(rs.getInt("age"));
    System.out.println(rs.getString("location"));
}

Connections, statements, and result sets maintain an open socket while they are in use. Therefore, once finished with the data processing invoke the close method to cleanup the resources.

try (Statement stmt = conn.createStatement()) {
    val rs = stmt.executeUpdate("SELECT * FROM mytopic");
}