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 bit.io 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 = "db.bit.io";
      String bitPort = "5432"; // We keep this as a string here as we are concact'ing it into the connection string
      Properties props = new Properties();
      props.setProperty("sslmode","require");
      props.setProperty("user",bitUser);
      props.setProperty("password",bitApiKey);
      try {
         Class.forName("org.postgresql.Driver");
         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 (rs.next()) {
             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) + " ");
             }
             System.out.println();
         }

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

The code above is available on github.


Did this page help you?