I'm using prepareStatement()
to prevent sql injection. the problem I have now is that with the method below, I can do getConnection().prepareStatement()
then build my query, but I'll need to try-catch on every single call to getConnection()
and close it in finally
block. createStatement().execute()
seems to be better because I could have client to pass in the query then handle try-catch-finally in one place, but it won't prevent sql injection. what is the best practice usually? or is there any other way to build query that can prevent sql injection?
private static Connection getConnection() throws SQLException, URISyntaxException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}