Let's say I have created a simple login window in JavaFX that checks if the username and password match each other by connecting to a postgresql database, and upon success logs the user in.
Now, this works perfectly fine as long as an internet connection exists.
However, if there's no internet connection the JVM repeatedly spews out PSQLExceptions and the application freezes for somewhat a minute or so. I thought I was catching these in my connection class. It is caused by SocketTimeoutException.
Does anyone have any tips regarding how I could handle this such that an error message would display in the GUI rather than freezing and exceptions?
My connection class looks like this:
public class DBConnection {
/* DB credentials, modify as needed */
private static final String HOST = "<HOST>";
private static final String DATABASE = "<DATABASE>";
private static final String USERNAME = "<USERNAME>";
private static final String PASSWORD = "<PASSWORD>";
private static final String PORT = "5432";
/* !!DO NOT EDIT BELOW!! */
private static final String JDBC_DRIVER = "org.postgresql.Driver";
private static final String URL = "jdbc:postgresql://" + HOST + ":" + PORT + "/" + DATABASE;
private static final ComboPooledDataSource POOL = new ComboPooledDataSource();
private static Connection conn = null;
public static void Connect() throws PropertyVetoException, SQLException{
try {
POOL.setDriverClass(JDBC_DRIVER);
}catch (PropertyVetoException e){
System.out.println("Could not locate JDBC driver");
e.printStackTrace();
throw e;
}
//Connection parameters
POOL.setJdbcUrl(URL);
POOL.setUser(USERNAME);
POOL.setPassword(PASSWORD);
//Pool properties
POOL.setMinPoolSize(3);
POOL.setAcquireIncrement(5);
POOL.setMaxPoolSize(100);
POOL.setMaxStatements(180);
try {
conn = POOL.getConnection();
} catch (SQLException e) {
System.out.println("Could not establish connection to database");
e.printStackTrace();
throw e;
}
}
public static ResultSet ExecuteQuery(String query) throws PropertyVetoException, SQLException {
PreparedStatement st = null;
ResultSet rs = null;
CachedRowSet crs = null;
try {
Connect();
System.out.println("Select statement: " + query + "\n");
st = conn.prepareStatement(query);
rs = st.executeQuery();
crs = new CachedRowSetImpl();
crs.populate(rs);
}catch (Exception e){
System.out.println("Problem occurred at executeQuery operation: " + e);
throw e;
}finally {
DbUtils.closeQuietly(conn, st, rs);
}
return crs;
}
public static void ExecuteUpdate(String query) throws PropertyVetoException, SQLException {
PreparedStatement st = null;
try {
Connect();
st = conn.prepareStatement(query);
st.executeUpdate();
}catch (Exception e){
System.out.println("Problem occurred at executeUpdate operation: " + e);
throw e;
}finally {
DbUtils.closeQuietly(st);
DbUtils.closeQuietly(conn);
}
}
}