[英]Insert Date in string format into a database having field type of Date
I am having a date in the following format as string. 我有以下格式的日期作为字符串。
String from_date = "2016-09-09";
I need to insert into into a database having date type field using PreparedStatement
. 我需要使用
PreparedStatement
插入具有日期类型字段的数据库中。 I have done it in the following way. 我已经按照以下方式完成了。
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fd = formatter.parse(from_date);
select1.setDate(1, fd);
But it is showing the error as 但是它显示错误为
The method setDate(int.java.sql.Date) in the type PreparedStatement is not applicable to the arguments(int,java.util.Date)
PreparedStatement类型的方法setDate(int.java.sql.Date)不适用于参数(int,java.util.Date)
You need to use a java.sql.Date
when inserting in database. 在数据库中插入时,需要使用
java.sql.Date
。 Try the following : 尝试以下方法:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fd = formatter.parse(from_date);
java.sql.Date sqlDate = new java.sql.Date(fd.getTime());
select1.setDate(1, sqlDate);
Answered here: Type mismatch: cannot convert from java.util.Date to java.sql.Date 在这里回答: 类型不匹配:无法从java.util.Date转换为java.sql.Date
You are trying to use a method that accepts java.sql.Date
instead of java.util.Date
您正在尝试使用接受
java.sql.Date
而不是java.util.Date
Welcome to programming, mind the details 欢迎编程,请注意细节
Suppose you have a variable endDate of type java.util.Date, you make the conversion thus: 假设您有一个类型为java.util.Date的endDate变量,则可以这样进行转换:
select1.setDate(1, new java.sql.Date(endDate.getTime());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.