I am quite new to Java, so for sure this is gonna be a silly question.
I often read that one must be aware of the risk of SQL injection when dealing with queries treated as String. I also read that using PreparedStatements is a good way for preventing such risk, but they are generally used with positional parameters in the query (represented by question marks ?
).
What about the case when I just have a "constant" query with no parameters (i.e., I have no variables to insert in my query)? Do I still have to pass the query in the form
"SELECT * from Table where col1 = ? and col2 = ?"
to the PreparedStatement to prevent SQL injection?
Or could I just pass
"SELECT * from Table where col1 = 123 and col2 = 'abc'"
?
I have this code:
public ResultSet mySelectMethod(String query, Connection conn) {
ResultSet rset = null;
try {
PreparedStatement st = conn.PreparedStatement(query); //I am unsure about this assignment
rset = st.executeQuery();
} catch (SQLException e) {
System.out.println(e);
}
return rset;
}
...
...
// method call:
String myQuery = "SELECT colA FROM table_name WHERE table_id = 192837465";
ResultSet myResultSet = mySelectMethod(myQuery, myConn);
Is this safe or are there any issues?
Since you are not passing any parameter to your query, you do not have the risk of SQL Injection. Also, you do not need PreparedStatement
for your case. You can use Statement
instead.
String query = "SELECT * from Table where col1 = 123 and col2 = 'abc'";
try (Statement st = conn.createStatement()) {
ResultSet rset = stmt.executeQuery(query);
while (rs.next()) {
//...
}
}
Apart from this, as you can see in the code above, you should try using try-with-resorces statement which closes the resource automatically.