是什么导致NullPointerException?

时间:2015-07-10 23:46:54

标签: java nullpointerexception javafx-8

我不知道为什么我有null尽管将代码与我之前编写的代码进行比较。

这是我将Java数据插入表格的代码:

  @FXML
    private void rewards_Parameters(){
        try{
            String sql = "INSERT INTO SetUpReward VALUES(?,?,?,?,?,?)";
            if(sql !=null){
                pst =con.prepareStatement(sql);
                pst.setString(2, txt_minGiftValue.getText());
                pst.setString(3, txt_maxGiftValue.getText());
                pst.setString(4, txt_RewardPoint.getText());

                pst.execute();
            }
        }catch(SQLException e){
            JOptionPane.showMessageDialog(null, e);
        }    
    }

我的初始化过程......

 /**
 * FXML Controller class
 *
 * @author JIDO
 */
public class IGisftCardController implements Initializable {
    Connection con =null;
    ResultSet rs = null;
  PreparedStatement pst ;

堆栈跟踪:

Caused by: 

java.lang.NullPointerException
    at view_controller.IGisftCardController.loadReward(IGisftCardController.java:249)
    at view_controller.IGisftCardController.initialize(IGisftCardController.java:168)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    ... 22 more
Exception running application igiftcardfx.IGiftCardFX
Java Result: 1

1 个答案:

答案 0 :(得分:1)

因为connull。您测试sql != null,将其设为con。你应该连接到一个数据库(或者至少是你不是的日志)。另外,请捕获堆栈跟踪(它们对于调试应用程序非常有用)。像,

String sql = "INSERT INTO SetUpReward VALUES(?,?,?,?,?,?)";
try {
    if (con != null) {
        pst = con.prepareStatement(sql);
        pst.setString(2, txt_minGiftValue.getText());
        pst.setString(3, txt_maxGiftValue.getText());
        pst.setString(4, txt_RewardPoint.getText());
        pst.setString(5, txt_CardNumber.getText());
        pst.setString(6, txt_PayPalEmail.getText());
        pst.setString(7, txt_BankName.getText());
        pst.setString(8, txt_BankAccount.getText());
        pst.execute();
    } else {
        System.out.println("No connection");
    }
} catch (SQLException e) {
    JOptionPane.showMessageDialog(null, e);
    e.printStackTrace();
}