Friday, December 1, 2017

How to prevent SQL injection attacks?

Using PreparedStatement, you can prevent SQL injection attacks.
try{
    String query = "INSERT INTO TB_USER"
        + "(COLUMN1, COLUMN2, COLUMN3, COLUMN4) VALUES"
        + "(?,?,?,?)";
    PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
    preparedStatement.setString(1, txt_nidn.getText());
    preparedStatement.setString(2, txt_nikdosen.getText());
    preparedStatement.setString(3, txt_namadosen.getText());
    preparedStatement.setString(4, txt_alamat.getText());
    preparedStatement .executeUpdate();
    JOptionPane.showMessageDialog(this,"Data Berhasil Di Simpan","Informasi",JOptionPane.INFORMATION_MESSAGE);
    gettabel();
    bersih();
} catch (SQLException ex){
    JOptionPane.showMessageDialog(null, "Proses Penyimpanan Gagal atau Cek Koneksi Anda!","Error",JOptionPane.ERROR_MESSAGE);
    System.out.println(ex.getMessage());
}
Please don't forget to change TB_USER column name. Replace all COLUMN1, COLUMN2, COLUMN3, COLUMN4 to your tables column name.
All credit goes to Jon Skeet.
Related Link:
  1. http://www.javatpoint.com/PreparedStatement-interface
  2. http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/
  3. http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm

No comments:

Post a Comment