使用JavaFX日期选择器将日期插入MySql数据库



我正试图使用javaFx从数据选择器向mysql数据库插入日期。我已经厌倦了提交这个代码。

@FXML
private DatePicker DPCurrentDate;//fx:id="DPCurrentDate"
// BrandAdded is a Method that i created for insert data into database
private void BrandAdded(){
    DBConnection newCon = new DBConnection();
    con = newCon.geConnection();
    try {
        pst = con.prepareStatement("insert into Brands values(?,?,?,?,?)");
        pst.setString(1, null);
        pst.setString(2, TFBrandName.getText());
        pst.setString(3, TABrandDecription.getText());
        pst.setString(4, lblUserName.getText());
        pst.setDate(5, DPCurrentDate.getValue());
        pst.executeUpdate();
    } catch (SQLException ex) {
        Logger.getLogger(AddBrandController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

当我运行程序时,它会给我这个错误

error: incompatible types: LocalDate cannot be converted to Date
        pst.setDate(5, DPCurrentDate.getValue());

您需要

java.util.Date date = 
    java.util.Date.from(dpCurrentDate.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant());
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
pst.setDate(5, sqlDate);

(使用java.sql.Date(.

import java.sql.Date;
Date  DPCurrentDate1 =  Date.valueOf(DPCurrentDate);
pst.setDate(5, DPCurrentDate1);

这将完成您的工作

在您的方法save或您命名的任何方法中使用它。

dateTimePicker.valueProperty().get(),

注意。如果这是您最后保存的项目,请使用)关闭它。

你可以试试这个:

pst.setDate(5, ((TextField)DPCurrentDate.getEditor()).getText());

最新更新