0

I know that using Statement and plain String is bad programming, and I need to use preparedStatement to avoid SQL Injections. But can I create string and then put the String into preparedStatement, or is this same as using Statement ?

for example:

String sql = "SELECT * FROM users WHERE user_ID = ?";

preparedStatement = connection.prepareStatement(sql);

preparedStatement.setLong(1, userId);
BlackHatSamurai
  • 21,845
  • 20
  • 84
  • 147

2 Answers2

2

You can use ps.setString, it is not the same as using a raw String query. The PreparedStatement is guaranteed to escape characters before sending them to the database, and your query should be immune to sql injection attacks (from that String anyway).

Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
0

The idea is to use the parameters given as input into your PreparedStatement as is instead of building your SQL commands, in such a case the following works just fine:

PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(`INPUT PARAMETER`);

If you don't abide by this, you are still VULNERABLE to SQL Injection attacks as you would be ending up concatenating strings.

Good Reads on this topic are these links:

  1. How can prepared statements protect from SQL injection attacks?
  2. http://javarevisited.blogspot.in/2012/03/why-use-preparedstatement-in-java-jdbc.html
  3. How does a PreparedStatement avoid or prevent SQL injection?
Community
  • 1
  • 1
N00b Pr0grammer
  • 3,930
  • 4
  • 28
  • 40