我正在尝试将 TextField 值保存到数据库中,但出现“java.lang.NullPointerException”。
我希望在调用“addClient()”方法时将客户的名字保存到数据库中。
谁能帮我让它工作?谢谢大家。
控制器类:
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import wakiliproject.Forms.AddNew.DB.NewClientDB;
public class NewClientController implements Initializable {
@FXML
public TextField firstName;
// Initializes the controller class.
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@FXML
public void addClient() throws SQLException {
new NewClientDB().main();
}
}
数据库类:
import Database.Plain.Skell.DBConnect;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import wakiliproject.Forms.AddNew.NewClientController;
public class NewClientDB extends NewClientController {
private String firstNames = new NewClientController().firstName.getText();
public void main() throws SQLException {
Connection conn = DBConnect.connect();
Statement stmt = null;
try {
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO KIWI "
+ "VALUES (102, " + (firstNames) + ")";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
}// do nothing
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}
编辑:
我忘了提到这是在 JavaFx 中,并且“TextField firstName”是从使用 JavaFx SceneBuilder 创建的 FXML 文件中调用的。我试过在控制器中初始化它,但没有成功。有任何想法吗?我认为这些类型的对象不应该被初始化,至少通过 JavaFx。
错误:
Caused by: java.lang.NullPointerException
at wakiliproject.Forms.AddNew.DB.NewClientDB.<init>(NewClientDB.java:12)
at wakiliproject.Forms.AddNew.NewClientController.addClient(NewClientController.java:41)
... 40 more