This question already has answers here:
What is a NullPointerException, and how do I fix it?
                            
                                (12个答案)
                            
                    
                2年前关闭。
        

    

我一直在尝试从txt1(jtextfield)中获取一个值,该值是我数据库中的一个ID。但是它一直说java.lang.NullPointerException。这是代码:

public void harga()
{

   try {
        stat = con.createStatement();
        String query = "SELECT harga from obat WHERE ID = '"+ Integer.valueOf(txt1.getText())+"'";
        stat.executeQuery(query);
        ResultSet rs = stat.getResultSet();
        while (rs.next()) {
            int harga = rs.getInt("harga");
            //String nama = rs.getString("nama");
            System.out.println(harga);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

最佳答案

首先@Sagar似乎是正确的,因为不能确保txt1中有可转换的值。为了确保您应该为txt1添加一个ChangeListener。
http://docs.oracle.com/javase/tutorial/uiswing/events/changelistener.html

其次,将查询并在一起是一个不好的做法,尤其是在查询参数来自UI的情况下。这背后的原因是您正在接受SQL注入。改用PreparedStatements
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

祝您编程愉快,并欢迎使用Stackoverflow!

09-28 02:05