SQL Injection - Avoiding

Avoiding

Sanitize data.

  • If the product id is an Int, validate the value before issuing a request.

  • Filter out invalid characters (but this has limited success!)

Use Prepared Statements.

  • Clear separation between structure and data.

  • Data cannot alter SQL query structure.

Prepared Statements Java

String firstname = req.getParameter("firstname");
String lastname = req.getParameter("lastname");

String query = "SELECT id, firstname, lastname FROM authors WHERE forename = ?
and surname = ?";

PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, firstname );
pstmt.setString( 2, lastname );
try
{
    ResultSet results = pstmt.execute( );
}

Last updated