2

Here is my code in java :

try{
    String query = "INSERT INTO tb_user VALUES ('"+txt_nidn.getText()+"','"+txt_nikdosen.getText()+"','"+txt_namadosen.getText()+"','"+txt_alamat.getText()+"')";
    stat = koneksi.createStatement();
    int res = stat.executeUpdate(query);
    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());
}

Is there something wrong in my code? I can't insert some data to database, because of these erroring. Please help me :(

2
  • 3
    "Is there something wrong in my code?" - Yes, it's horribly vulnerable to SQL injection attacks. The very first thing to fix is that. Use parameterized SQL with PreparedStatement. Once you've done that, it'll be much easier to see the details of the SQL, and the other errors will be fixed more easily. (I'd specify the columns explicitly too, personally...) Commented Mar 11, 2016 at 17:39
  • error message is very clear, tb_user doesn't have 4 columns, check your table Commented Mar 11, 2016 at 17:41

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.