JavaFX 无法将数字添加到数据库列

标签 java javafx

如果这是重复的,我很抱歉,但我还没有找到答案。

我正在开发一个在 JavaFX 中运行基本库存管理系统的项目。我目前正在尝试允许用户将新项目添加到 SQLite 数据库中,虽然 ID 和项目名称很好地添加到数据库中,但输入到文本字段中的初始值似乎被忽略了。

程序在可用单位字段中输入值 0.0。这是我当前的代码:

Main.java

package sample;

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;

    public class Main extends Application {

        @Override
        public void start(Stage primaryStage){
            try {
                Parent root = FXMLLoader.load(getClass().getResource("DatabaseView.fxml"));

                Scene scene = new Scene(root);

                primaryStage.setTitle("Brewer's Guide Inventory Management");

                primaryStage.setScene(scene);
                primaryStage.show();
            } catch (Exception e){
                e.printStackTrace();
            }
            }

        public static void main(String[] args) {
            launch(args);
        }
    }

beerDatabaseData.java

    package sample;

    import javafx.beans.property.DoubleProperty;
    import javafx.beans.property.SimpleDoubleProperty;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;

    public class beerDatabaseData {

        private final StringProperty ID;
        private final StringProperty name;
        private DoubleProperty units;

        public beerDatabaseData (String ID, String Name, Double Units)
        {
            this.ID = new SimpleStringProperty(ID);
            this.name =  new SimpleStringProperty(Name);
            this.units = new SimpleDoubleProperty(Units);
        }

        public StringProperty IDProperty()
        {
            return this.ID;
        }

        public String getID()
        {
            return this.IDProperty().get();
        }

        public void setID(final String ID)
        {
            this.IDProperty().set(ID);
        }

        public StringProperty nameProperty()
        {
            return this.name;
        }

        public String getName()
        {
            return this.nameProperty().get();
        }

        public void setName(final String name)
        {
            this.nameProperty().set(name);
        }

        public DoubleProperty unitsProperty()
        {
            return this.units;
        }

        public Double getUnits()
        {
            return this.unitsProperty().get();
        }

        public void setUnits(Double units)
        {
            this.unitsProperty().set(units);
        }
    }

数据库 View Controller

package sample;

/*
Add method to auto-load data rather than pressing button (possible on-load).
Look at dependency injection (inversion of control (if possible) for testing).
Malt service (all actions with malt data).
Separation of concerns.
 */

//https://stackoverflow.com/questions/50358299/javafx-populating-multiple-tables-in-separate-tabs
//https://stackoverflow.com/questions/41465181/tableview-update-database-on-edit
//https://stackoverflow.com/questions/45977390/how-to-force-a-double-input-in-a-textfield-in-javafx

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class DatabaseViewController {
    @FXML
    private TextField idNumberInput1, idNumberInput2;

    @FXML
    private TextField nameInput1, nameInput2;

    @FXML
    private TextField unitsInput1, unitsInput2;

    @FXML
    private TableView<beerDatabaseData> beerTab1, beerTab2;

    @FXML
    private TableColumn<beerDatabaseData, String> ID1, ID2;

    @FXML
    private TableColumn<beerDatabaseData, String> name1, name2;

    @FXML
    private TableColumn<beerDatabaseData, Double> units1, units2;

    /*private ObservableList<DatabaseData> data;*/

    public void initialize(URL location, ResourceBundle resource) {
        //
    }

    private ObservableList<beerDatabaseData> data1;
    private ObservableList<beerDatabaseData> data2;

    public void LoadData(ActionEvent event) throws SQLException {
        try {
            Connection conn = SQLConnection.Connector();
            this.data1 = FXCollections.observableArrayList();
            this.data2 = FXCollections.observableArrayList();

            ResultSet rs1 = conn.createStatement().executeQuery("SELECT * FROM Malts");
            while (rs1.next()) {
                this.data1.add(new beerDatabaseData(rs1.getString(1), rs1.getString(2), rs1.getDouble(3)));
            }
            ResultSet rs2 = conn.createStatement().executeQuery("SELECT * FROM HOPS");
            while (rs2.next()) {
                this.data2.add(new beerDatabaseData(rs2.getString(1), rs2.getString(2), rs2.getDouble(3)));
            }

        }catch (SQLException e) {
            System.out.println(e);
        }

        this.ID1.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("ID"));
        this.name1.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("Name"));
        this.units1.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, Double>("Units"));

        this.beerTab1.setItems(null);
        this.beerTab1.setItems(this.data1);

        this.ID2.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("ID"));
        this.name2.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, String>("Name"));
        this.units2.setCellValueFactory(new PropertyValueFactory<beerDatabaseData, Double>("Units"));

        this.beerTab2.setItems(null);
        this.beerTab2.setItems(this.data2);
    }

    //Separating add functions for each ingredient since things are a little different for each.
    public void addMalt(ActionEvent event){
        try
        {
            Connection conn = SQLConnection.Connector();
            PreparedStatement Prs = conn.prepareStatement("INSERT INTO Malts(Malt_ID,Malt_Name, Malt_Units) VALUES(?, ?, ?)");

            Prs.setString(1,this.idNumberInput1.getText());
            Prs.setString(2, this.nameInput1.getText());

           /* Pattern validEditingState = Pattern.compile("-?(([1-9][0-9]*)|0)?(\\.[0-9]*)?");

            UnaryOperator<TextFormatter.Change> filter = c -> {
                String text = c.getControlNewText();
                if(validEditingState.matcher(text).matches()){
                    return c;
                }
                else{
                    return null;
                }
            };

            StringConverter<Double> converter = new StringConverter<Double>() {
                @Override
                public Double fromString(String s) {
                    if (s.isEmpty() || "-".equals(s) || ".".equals(s) || "-.".equals(s)){
                        return 0.0;
                    } else{
                        return Double.valueOf(s);
                    }
                }

                @Override
                public String toString(Double d) {
                    return d.toString();
                }
            };

            TextFormatter<Double>  textFormatter = new TextFormatter<>(converter, 0.0, filter);
            unitsInput1.setTextFormatter(textFormatter);
*/
            Prs.setString(3, this.unitsInput1.getText());

            Prs.execute();

            conn.close();
        }
        catch(SQLException e)
        {
            System.out.println(e);
        }
    }

/*    public void addHops(ActionEvent event){
        try
        {
            Connection conn = SQLConnection.Connector();

        }
        catch(SQLException e){
            System.out.println(e);
        }
    }*/
}

我认为有一个明显的问题导致了这种情况,但我没有看到它。我需要更改或包含哪些内容才能使其正常工作?提前谢谢您。

最佳答案

看起来表中的 Malt_Units 列是数字,但您尝试将其作为字符串插入。您应该解析输入中的值,然后将其设置为 Double:

Prs.setDouble(3, Double.parseDouble(this.unitsInput1.getText()));

关于JavaFX 无法将数字添加到数据库列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005605/

相关文章:

java - Class.forName() 不断显示错误 : java. lang.NullPointerException

java - 在黑莓中将自定义浏览器设置为默认浏览器

Java Windows/Linux 程序 Alt Tab 循环

javafx-2 - 在 JavaFX 中创建向导

java - Mongotemplate聚合-获取结果数

java - Google App Engine 仅更新具有许多有效 java 的实体的一个属性

JavaFX 更改不同类的 Pane 颜色

来自 Controller 的 JavaFX 转换场景

Javafx:对话框 y 位置无法正常工作

java - Wicket:获取浏览器信息