package database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * Create a persistent database connection. * * @author Maurice Laveaux */ public class DBConnection { /* The interface to the postgresql database connection. */ private Connection m_connection; public DBConnection(final String hostaddress, final String port, final String databasename, final String username, final String password) { String url = "jdbc:postgresql://" + hostaddress + ":" + port + "/" + databasename; try { m_connection = DriverManager.getConnection(url, username, password); } catch (SQLException ex) { //TODO: retry when db connection fails or something. throw new RuntimeException("cannot connect to host: " + url); } } /** * prepares a statement. * * @param query The query to prepare. * @return A prepared statement. */ public PreparedStatement create(final String query) throws SQLException { return m_connection.prepareStatement(query); } /** * Closes the connection if it exists. */ public void close() { if (m_connection != null) { try { m_connection.close(); } catch (SQLException ex) { /* TODO: what to do here else. */ Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex); } } } }