1

I have code like this

String sql_kode_kategori = "select kategori from data_kategori \n" +
                                   "where kode_kategori = ?";
    try{
        pst = (PreparedStatement) koneksiMySQL.GetConnection().prepareStatement(sql_kode_kategori);
        pst.setString(1, (String)cbKategori.getSelectedItem());
        rst2 = pst.executeQuery();
        rst2.next();

        stat = (Statement) koneksiMySQL.GetConnection().createStatement();
        String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
                + ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
        stat.executeUpdate(sql_insert);
        javax.swing.JOptionPane.showMessageDialog(null, "Data CES Berhasil Ditambahkan");
        ClearField();
        TampilTabel();

    }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }

i tried to get kode_kategori with kategori but that error appear, please help me

3
  • 1
    First thing to do: stop inserting values directly into your SQL. Use parameterized SQL, as you're already doing for the query part. Commented Dec 7, 2015 at 13:16
  • 1
    If rst2.next() returns false, there is no data for rst2.getString(1). You need to check for result as if(rst2.next()) { Commented Dec 7, 2015 at 13:18
  • can you give me some example on source code ? Commented Dec 7, 2015 at 13:19

2 Answers 2

1

If rst2.next() returns false, there is no data for rst2.getString(1). You need to check for result as

if(rst2.next()) { 
    stat = (Statement) koneksiMySQL.GetConnection().createStatement();
    String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
            + ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
    stat.executeUpdate(sql_insert);
} else {
  // handle invalid category
}
Sign up to request clarification or add additional context in comments.

2 Comments

program can't run with that way
? Please explain. Do you get errors? Not compiling?
0

Remove \n from your query:

 String sql_kode_kategori = "select kategori from data_kategori where kode_kategori = ?";

Try to verify this (String)cbKategori.getSelectedItem() variable does contain right value.

3 Comments

@Pramesty Jaya Try to verify this (String)cbKategori.getSelectedItem() variable does contain right value.
that's part work perfectly, nothing wrong on that part
oh god, my bad. I want to get kode_kategori use kategori, i use wrong query. Thanks man

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.