1

I'm using Java for a web application, and I'm working with a MySql database. I need to escape the query before execute it. This is my actual code :

db_result=mydb.selectQuery("SELECT nickname FROM users WHERE nickname='"+log_check_user+"' AND password='"+log_check_pass+"'");

public Vector selectQuery(String query) {
  Vector v = null;
  String [] record;
  int colonne = 0;
  try {
     Statement stmt = db.createStatement();
     ResultSet rs = stmt.executeQuery(query);
     v = new Vector();
     ResultSetMetaData rsmd = rs.getMetaData();
     colonne = rsmd.getColumnCount();

     while(rs.next()) {
        record = new String[colonne];
        for (int i=0; i<colonne; i++) record[i] = rs.getString(i+1);
        v.add( (String[]) record.clone() );
     }
     rs.close();
     stmt.close();
  } catch (Exception e) { e.printStackTrace(); errore = e.getMessage(); }

  return v;
 }

I need this, as you can believe, to avoid the SQL Injection problem! How can I do it?

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
markzzz
  • 47,390
  • 120
  • 299
  • 507

1 Answers1

18

Use a prepared statement:

Sometimes it is more convenient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from the more general class, Statement...

If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead.

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first...

gnat
  • 6,213
  • 108
  • 53
  • 73
Joshua Martell
  • 7,074
  • 2
  • 30
  • 37
  • +1. Also, Vector is considered to be deprecated, see http://stackoverflow.com/questions/1386275/why-java-vector-class-is-considered-obsolete-or-deprecated – Qwerky Nov 10 '10 at 15:34
  • 2
    In all discussions of SQL injection, this link is compulsory: http://xkcd.com/327/ – JeremyP Nov 10 '10 at 16:17