Kevin B
asked on
Getting "Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections" when connecting via jdbc
Hi, I am using JDBC to connect to a Postgres DB. I am calling a method that connects to the DB twice. It connects once to do a select statement and another time to do an insert statement. I am checking to see if the a session_id exists and if it doesn't I am adding the session_id into the DB. It does the initial select fine, but when I try to connect the second time to do the insert I am getting the error in the title above. Here is what my code looks like. Can anyone help me out with resolving this?
private void initialInsert(String sessionId) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
log.info("Class Not Found: " + e.getMessage());
}
log.info("Entering the initial insert");
String sessionIdFromDB = "";
String url = "jdbc:postgresql://10.233.52.71:5432/CustomersLikeYou";
Properties props = new Properties();
props.setProperty("user", "itrd");
props.setProperty("password", "itrd");
Connection conn = null;
ResultSet rs = null;
try {
log.info("Entering select");
conn = DriverManager.getConnection(url, props);
Statement statement = conn.createStatement();
rs = statement.executeQuery(
"select session_id from public.individual_customer where session_id = '" + sessionId + "'");
log.info("Succeful select");
while (rs.next()) {
if (StringUtils.isNotEmpty(rs.getString("session_id"))) {
sessionIdFromDB = rs.getString("session_id");
}
}
} catch (SQLException e) {
log.info(e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.info(e.getMessage());
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.info(e.getMessage());
}
}
}
try {
log.info("Entering insert");
conn = DriverManager.getConnection(url, props);
Statement statement = conn.createStatement();
if (StringUtils.isEmpty(sessionIdFromDB)) {
// insert session id
statement.executeUpdate(
"insert into public.individual_customer (session_id) values '" + sessionId + "'");
}
log.info("Successful insert");
} catch (SQLException e) {
log.info(e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.info(e.getMessage());
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.info(e.getMessage());
}
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks!