The problem with your query is that you're appending the value of info into the query literal, but not wrapping it within single quotes as is required in PostgreSQL. So, the query that's sent over to the DB becomes something like
SELECT EXISTS(SELECT 1 FROM myTable WHERE info=valueOfInfo)
instead of
SELECT EXISTS(SELECT 1 FROM myTable WHERE info='valueOfInfo')
The correct way to do this is to use bind variables with the PreparedStatement and only have placeholders (?) in the query literal. This way, you don't need to worry about wrapping the variable in quotes, or more importantly, the possibility of SQL injection.
Additionally, you should take care of closing the statement after use; this is easiest done with the try-with-resources statement (assuming you're on Java 7 or above). So the fixed version of your method could look something like this:
public boolean checkExist(String table, String info) {
final String query = "SELECT EXISTS(SELECT 1 FROM " + table
+ " WHERE info = ?)";
try (PreparedStatement st = con.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
st.setString(1, info); // bind the variable to the placeholder
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
return rs.getBoolean(1); // EXISTS() returns a boolean
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
exists. How can you have aselectwithout afrom?FROMclause can be omitted here becauseEXISTSis a subquery expresssion which always returns a boolean. The root of the problem lays in the misuse ofPreparedStatement; instead of using a bind variable, theinfovariable is simply conctenated into the query, but the surrounding single quotes are missing."SELECT EXISTS(SELECT 1 FROM " + table + " WHERE info= '" + info + "')"should work, but even that would be "doing it wrong".