简体   繁体   中英

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 . 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)

You need to use a java.sql.Date when inserting in database. 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

You are trying to use a method that accepts java.sql.Date instead of java.util.Date

Welcome to programming, mind the details

Using java.sql.Date

java.util.Date

Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:

 select1.setDate(1, new java.sql.Date(endDate.getTime());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM