gpt4 book ai didi

java.lang.NullPointerException 和结果集

转载 作者:行者123 更新时间:2023-12-03 23:14:52 24 4
gpt4 key购买 nike

这是我的第一篇文章,请耐心等待。我正在开发一个 java 项目,它连接到一个 sql 数据库。我目前正在尝试做的是,当我单击一个按钮时,将在我的数据库的文本区域中显示具有指定 ID 的项目名称和项目价格。但是,当我单击按钮时,会出现如下错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at OrderFrame.waterButtonActionPerformed(OrderFrame.java:494)
at OrderFrame.access$000(OrderFrame.java:11)

这是我的 waterButtonActionPerformed 的代码:

private void waterButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
// TODO add your handling code here:
try{

String query;
query = "SELECT itemName, itemPrice FROM item WHERE itemID = '11111'";
String itemName = " ",itemPrice =" ";

***ResultSet rs = st.executeQuery(query);***

if(rs != null){
while(rs.next())
{
itemName = rs.getString(1);
itemPrice = rs.getString(2);
}
orderTextArea.setText(itemName);
orderTextArea.setText(itemPrice);
}
} catch (SQLException ex) {}
}

第 494 行是 ResultSet 的声明。我希望有人能帮我解决这个问题。提前谢谢你。

最佳答案

像这样重写处理程序:

waterButton.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
Statement st = connectionObject.createStatement();

// might want to use placeholders here as well
String query= "SELECT itemName, itemPrice FROM item WHERE itemID = '11111'";
String itemName = " ",itemPrice =" ";

ResultSet rs = st.executeQuery(query);

if(rs != null){
do {
itemName = rs.getString(1);
itemPrice = rs.getString(2);
} while (rs.next());
orderTextArea.setText(itemName);
orderTextArea.setText(itemPrice);
}
} catch (SQLException ex) {
System.err.println(new java.util.Date()+" : "+ex.getMessage();
}
});

关于java.lang.NullPointerException 和结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15794369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com