Connecting via Java & JDBC

First, download the latest version of the Postgres JDBC driver, and put that jar file in your project's classpath (or, add this dependency to Maven)

All you need to know to use Java with is your connect string - you can find this by clicking on the green "connect" button on your repo. You can paste that string right into your code as the connection url, or you can copy from the example below on how to configure the connect string with variables.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Properties;

public class BitioExample {
   public static void main(String args[]) {
      Connection c = null;
      String bitApiKey = "<your api key>";
      String bitDB = "sensors";
      String bitUser = "adam";
      String bitHost = "";
      String bitPort = "5432"; // We keep this as a string here as we are concact'ing it into the connection string
      Properties props = new Properties();
      try {
         c = DriverManager
            .getConnection("jdbc:postgresql://" + bitHost + ":" + bitPort + "/" + bitDB, props);
         Statement stmt = c.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM \"adam/sensors\".\"measurements\" order by datetime desc;" );
         while ( {
             ResultSetMetaData rsmd = rs.getMetaData();
             // The ResultSet .getXXX() methods expect the column index to start at 1. 
             // No idea why.
             for (int i = 1; i <= rsmd.getColumnCount(); i++) {
               System.out.print(rsmd.getColumnName(i) + "="+ rs.getString(i) + " ");

      } catch (Exception e) {
         System.err.println(e.getClass().getName()+": "+e.getMessage());

The code above is available on github.

Did this page help you?