java - 在 Java 中使用 GUI jButton 更新 JDBC 会导致 java.lang.NullPointerException
问题描述
我写了这两个类。首先是我创建的 GUI,其次是 Java 和 SQL 之间的 JDBC 连接器。我想在我的代码中添加一条更新语句,但无论我尝试了什么,我都会得到同样的错误。
这是一个大学项目。我已经尝试过 Prepared Statement 而不是 Statement,我已经测试了这个查询:
String query = "UPDATE user SET name = 'TEST' WHERE username = 'cleogeo'";
而不是代码中的那个,我知道连接、getter 和 setter 工作正常,因为程序的其余部分执行得很好。
CandidateUI 类 (GUI):这里我在 GUI 中创建“编辑和保存模式”,以便用户更轻松地更改他的个人资料设置。
private void EditAndSaveActionPerformed(java.awt.event.ActionEvent evt) {
counter++;
if(counter%2 == 1){
changePassword.setEditable(true);
changeName.setEditable(true);
changeSurname.setEditable(true);
changeEmail.setEditable(true);
changeBio.setEditable(true);
EditAndSave.setText("Save");
} else {
changePassword.setEditable(false);
changeName.setEditable(false);
changeSurname.setEditable(false);
changeEmail.setEditable(false);
changeBio.setEditable(false);
EditAndSave.setText("Edit");
newPassword = changePassword.getText();
newName = changeName.getText();
newSurname = changeSurname.getText();
newEmail = changeEmail.getText();
newBio = changeBio.getText();
iCRUDImpl.getCandidateUI(changeUsername.getText());
}
}
然后我为每个“新”变量创建 getter 和 setter。
ICRUDImpl 类(JDBC):
public CandidateUI getCandidateUI(String username) {
try{
CandidateUI candidateUI = new CandidateUI();
Statement statement = connection.createStatement();
String query = "UPDATE user SET password = '" + candidateUI.getNewPassword() + "', name = '" + candidateUI.getNewName() + "', surname = '" + candidateUI.getNewSurname() + "', email = '" + candidateUI.getNewEmail() + "' WHERE username = '" + username + "';UPDATE candidate SET bio = '" + candidateUI.getNewBio() + "'";
statement.executeUpdate(query);
return candidateUI;
} catch (SQLException e) {
return null;
}
}
我得到的错误是一个 java.lang.NullPointerException in line
Statement statement = connection.createStatement();
的 JDBC。
这也是我的连接方法:
public void openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/erecruit", "root", "");
System.out.println("Connection established successfully with the database server.");
} catch (ClassNotFoundException | SQLException e) {
System.err.println("Error: " + e.getMessage());
}
}
解决方案
ANullPointerException
表示您尝试访问的变量当前设置为 null,因此无法使用它。在您的情况下,connection
设置为null
,这意味着您将无法调用createStatement
。
为了解决您的问题NullPointerException
,您需要找到代码中connection
设置为不同于null
. 很可能该操作是在您的ICRUDImpl
类中无法访问的上下文中完成的,并且从未设置过相应的值ICRUDImpl
,从而导致您观察到的异常。
由于特定的“违规行”(或缺少这些行)严格取决于您的代码,如果您仍然遇到问题,请尝试准备一个片段,我们可以在 GitHub 等平台上运行或发布示例项目供我们查看。
推荐阅读
- c++ - 过滤掉不必要的词(即没有内涵的词)
- python - 使用 docutils 解析和编写 RST
- javascript - 节点mysql查询在最初正确记录后返回未定义的变量
- sql-server-2016 - SQL Server 2016,Web 版复制选项
- azure-data-explorer - Kusto:将所有列投影为字符串
- python - 在python多处理中使用进程之间的共享值终止循环
- firebase - 使用 Firebase 在 Flutter 中处理 iOS 和 Android 通知负载
- haskell - Haskell:如何检测“惰性内存泄漏”
- c++ - 从向量中提取 uint8_t* 子集
- javascript - 仅使用 vanilla JS 制作手风琴布局时元素的高度问题