Java Example

The following code example shows how to connect to the database and execute a query from a Java application.

Figure 1. Connecting to the database in a Java program
import java.sql.*;
//import java.util.*;

public class VRSConnection {
  // Replace "vrsHost" with the host name or IP address
  // of the Vocera Report Server.
  static String sHost = "vrsHost";   
  static String sUsername = "vocera";
  static String sPassword = "vocera";
  static String sThinConn = "jdbc:mysql://" + sHost + 
                            "/vocera_reports";
  static String driverClass = "com.mysql.jdbc.Driver";

  public static Connection getConnection() 
                                   throws SQLException {
    Connection c = null;
    try {
      Class.forName(driverClass).newInstance();
      c = DriverManager.getConnection(sThinConn, 
                                      sUsername, 
                                      sPassword);
    }  
      catch (Exception e) {
      e.printStackTrace(System.out);
    } 
    return c;
  }

  public static void main(String argv[]) {
    try {
      Connection conn = getConnection();
      if (conn == null) {
        System.out.println("No connection."); System.exit(0);
      }
      else {
        System.out.println("Connected.");
        Statement stmt = conn.createStatement();
        String query = "SELECT SITENAME FROM SITES";
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            System.out.println(rs.getString("SiteName"));
        }
        conn.close();
        System.out.println("Connection closed.");
      }
    }
    catch (SQLException sqle) {
      sqle.printStackTrace();
    }
  }
}