Java 从 jDateChooser 获取值并保存到 MS sql DB

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23564363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:59:37  来源:igfitidea点击:

getting value from jDateChooser and saving to MS sql DB

javasql-serverswingjdatechooser

提问by user3498019

I have two jDateChooser on my dialog , I want to save to MS-SQL DB having issue with that data types. Any idea how to fix this issue ! I can only do this when i convert data type to nvarchar in DB and convert the value to string which returns from jDateChooser.

我的对话框中有两个 jDateChooser,我想保存到 MS-SQL DB 中,但这些数据类型有问题。知道如何解决这个问题!我只能在将数据类型转换为 DB 中的 nvarchar 并将值转换为从 jDateChooser 返回的字符串时才能执行此操作。

enter image description here

在此处输入图片说明

// I can save in this way but I it doesn't use jDateChooser;

// 我可以用这种方式保存,但我不使用 jDateChooser;

   java.util.Date utilDate = new java.util.Date();
   java.sql.Date sqldate = new java.sql.Date(utilDate.getTime());

// I cant save the date with jDateChooser

// 我不能用 jDateChooser 保存日期

    java.sql.Date sqldate = new java.sql.Date(jDateChooser3.getDate());

// Only Way I found

// 我找到的唯一方法

  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

  String sd = dateFormat.format(jDateChooser3.getDate());

  obj.setStartDate(sd);

//

//

采纳答案by icza

Judging from the code you posted it looks like jDateChooser3.getDate()returns a java.util.Dateinstance while the java.sql.Date(millis)constructor expects the date/time as a longmilliseconds value.

从您发布的代码来看,它看起来像jDateChooser3.getDate()返回一个java.util.Date实例,而java.sql.Date(millis)构造函数将日期/时间作为long毫秒值。

Use this code and it will work:

使用此代码,它将起作用:

java.sql.Date sqldate = new java.sql.Date(jDateChooser3.getDate().getTime());

Since it comes from a date chooser component, invalid input most likely results in nullreturned date, so you might want to also check on that:

由于它来自日期选择器组件,无效输入很可能会导致null返回日期,因此您可能还想检查一下:

java.util.Date d = jDateChooser3.getDate();
if (d == null) {
    System.out.println("No date specified!");
} else {
    java.sql.Date sqldate = new java.sql.Date(d.getTime());
    // Do something with sqldate
}

回答by JustALady

Right click on jDateChooser. Go to the Properties and dateFormatString. Set this format: dd-MM-yyyy.

右键单击 jDateChooser。转到属性和 dateFormatString。设置此格式:dd-MM-yyyy。