how to prevent SQL-injectie java code example

Example 1: how to prevent sql injection in java

// This should REALLY be validated too
String custname = request.getParameter("customerName");
// Perform input validation to detect attacks
String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";
PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, custname);
ResultSet results = pstmt.executeQuery( );

Example 2: how to prevent sql injection in java

public List<AccountDTO>  unsafeFindAccountsByCustomerId(String customerId)  throws SQLException {    // UNSAFE !!! DON'T DO THIS !!!    String sql = "select "      + "customer_id,acc_number,branch_id,balance "      + "from Accounts where customer_id = '"      + customerId       + "'";    Connection c = dataSource.getConnection();    ResultSet rs = c.createStatement().executeQuery(sql);    // ...}

Tags:

Sql Example