[英]JavaFX - Insert form textfield to SQLite Database
我在應用程序中創建了一個Form場景,並想在單擊“保存”按鈕時將輸入的數據插入到SQLite數據庫中。 這是短代碼:
@FXML
private void handleSaveNewShop(ActionEvent event) {
String name = shopname.getText();
String adress = streetadress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText().toString();
Connection conn = null;
Statement stmt = null;
try{
Class.forName("org.sqlite.JDBC");
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection("jdbc:sqlite:FranchiseManagement.sqlite");
System.out.println(" SUCCESS!\n");
/*Tried this
String insertToshopList = "INSERT INTO shopList (name, adress, city, state, country, zipcode, phonect, phonearea, phonemain)" + "values(name,adress,city,state,country,zip,phonept1,phonept2,phonept3)";
stmt.executeUpdate(insertToshopList);
*/
//And This
//stmt.executeUpdate( "INSERT INTO shopList ('name','adress','city', 'state', 'country', 'zipcode', 'phonect', 'phonearea', 'phonemain') VALUES('"+name+"','"+adress+"','"+city+"'),'"+state+"','"+country+"','"+zip+"','"+phonept1+"','"+phonept2+"','"+phonept3+"'");
conn.commit();
System.out.println(" SUCCESS!\n");
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
但是我在提交的部分上遇到了NullPointException。 數據庫連接似乎正常並且已連接。
通過刪除提交進行了修復,並將INSERT添加到格式正確的方法中:
@FXML
private void handleSaveNewShop(ActionEvent event) {
String name = shopname.getText();
String adress = streetadress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText();
Connection conn;
Statement stmt = null;
try{
Class.forName("org.sqlite.JDBC");
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection("jdbc:sqlite:FranchiseManagement.sqlite");
System.out.println(" SUCCESS!\n");
stmt = conn.createStatement();
stmt.executeUpdate( "INSERT INTO shopList ('name','adress','city', 'state', 'country', 'zipcode', 'phonect', 'phonearea', 'phonemain') VALUES('"+name+"','"+adress+"','"+city+"','"+state+"','"+country+"','"+zip+"','"+phonept1+"','"+phonept2+"','"+phonept3+"')");
//conn.commit();
System.out.println(" SUCCESS!\n");
conn.close();
} catch (ClassNotFoundException | SQLException e){
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.