Search code examples
javasqljdbcsql-injection

Avoiding SQL injection in java


I am new to JavaEE and trying to learn to make a simple login page by checking the database. Here is the code sample:

ResultSet result=null;
Statement s = (Statement) con.createStatement();
result=s.executeQuery("select username from Table where ID="+id and " password="+password);

It should be vulnerable to SQL injection right? I would do this by using parametrized query in ASP.NET like the following:

SqlConnection con = new SqlConnection();
SqlCommand cmd=new SqlCommand("select username from Table where ID=@id and password=@password",con);    
cmd.Parameters.AddWithValue("@id", id); 
cmd.Parameters.AddWithValue("@password", password);  

Is there any way to use parametrized queries in Java like this? Can anyone use that query in parametrized form to avoid SQL injection?


Solution

  • Yes you can do this with PreparedStatement; for example:

    PreparedStatement preparedStatement = con.PreparedStatement(
            "SELECT * FROM MY_TABLE WHERE condition1 = ? AND condition2 = ?");
    preparedStatement.setString(1,condition1_value);
    preparedStatement.setString(2,condition2_value);
    ResultSet rs = preparedStatement.executeQuery();