Reyta Bonita
Reyta Bonita

Reputation: 21

How I can solve these Column count doesn't match value count at row 1?

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 :(

Upvotes: 2

Views: 141

Answers (1)

SkyWalker
SkyWalker

Reputation: 29168

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

Upvotes: 2

Related Questions