/* * DbBaseConnect.java */ package uw.ischool.info340.labs; import javax.naming.*; import javax.sql.*; import java.sql.*; public class DbBaseConnect { /* CHECK that this connection string is right * a) dhendry == is the name of the database * b) 5432 is the port number -- it is optional * c) linux.ischool.washington.edu -- is the name of the host */ private static String cDB_URL_STRING = "jdbc:postgresql://linux.ischool.washington.edu:5432/dhendry"; /* * NOTE: Check that the user ID and password are correct */ private static String cUserID = "dhendry"; private static String cUserPassword = "bluemonster"; /* This is the name of the JDBC driver for using postgresql */ private static String cDRIVER_STRING = "org.postgresql.Driver"; /* Holds the connection to database -- created by init() */ /* By default, transactions are auto-committed */ /* NOTE: Subclasses will need to use this BUT not clients */ protected Connection conn = null; /* * Used to hold error messages */ protected String debugString; /* * Returns of a string containing basic information about the connection */ private String _getConnInfo() { String t = "["; t += "Driver:" + cDRIVER_STRING + ";"; t += "DB URL: " + cDB_URL_STRING + ";"; t += "UserID: " + cUserID + ";"; t += "Password: " + cUserPassword + ";"; t += "]
" + debugString; return t; } /** * Returns information about the connection */ public String getConnectInfo() { if (conn != null) return "Connection up! " + _getConnInfo(); else return "Connection DOWN " + _getConnInfo(); } /** * Return true if the connection has been initialized */ public boolean isConnected() { return (conn == null) ? false : true; } /* * Subclasses MUST call this to initialize the connection */ public void init() { // Already initialized if (conn != null) { return; } try { /* This statement implicitly loads the driver */ Class.forName(cDRIVER_STRING); /* Now, attempt to create a connection */ conn = DriverManager.getConnection(cDB_URL_STRING,cUserID,cUserPassword); if (conn == null) throw new Exception("Could not connect to " + getConnectInfo()); } catch(Exception e) { debugString = e.toString(); e.printStackTrace(); } } }