我有一个来自面板的按钮代码,如下所示:
try{
Koneksi objKoneksi = new Koneksi();
Connection kon = objKoneksi.bukaKoneksi();
Statement stat = kon.createStatement();
String query = "insert into transaksi(invoiceno,kode,nama,jumlah,harga,total) values('"
+Invoice.getText()+"','"
+Kode.getText()+"','"
+Nama.getText()+"','"
+Jumlah.getText()+"','"
+Harga.getText()+"','"
+Total.getText()+"','";
int rows = stat.executeUpdate(query);
if(rows==1){
JOptionPane.showMessageDialog(this,"Data sudah tersimpan");
kon.close();
}
}
catch(SQLException e){}
}
还有一个Connection类:
和陈述类:
(很抱歉没有在这里发布代码。我在预先格式化的文本块上遇到了一些麻烦)
当我点击按钮将数据保存到数据库时,出现错误:
Connection success:
You are not connected to database
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javafinalproject.Aplikasi.SaveActionPerformed(Aplikasi.java:184)
at javafinalproject.Aplikasi.access$200(Aplikasi.java:15)
at javafinalproject.Aplikasi$3.actionPerformed(Aplikasi.java:83)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)dd
许多主题
有人可以帮我吗? 先谢谢
答案 0 :(得分:2)
此处发生异常:
catch (Exception ex) {
System.out.println("You are not connected to database");
return null;
}
您正在禁止它,您应该通过ex.printStackTrace()
显示它。
无论如何,该方法然后返回null
,这导致NullPointerException
在这里:
Statement stat = kon.createStatement();
// --------------^^^
<强>更新强>
把它放在这里:
catch (Exception ex) {
System.out.println("You are not connected to database");
ex.printStackTrace();
return null;
}
PS:你最好的选择是和你的老师/教授谈谈,看来你缺乏解决这个问题所需的基本理解。 子>