1

I am setting values to send queries in my DBUtil file, however two values: start, end - are Date type value in the HTML5 form and in the MySQL DB. How do I handle them in my DBUtil file while setting?

myStmt.setInt(1, theBook.getNumber());
myStmt.setInt(2, theBook.getPhone());
myStmt.setDate(3, theBook.getStart());
myStmt.setDate(4, theBook.getEnd());
myStmt.setString(5, theBook.getName());

in my Java class, DBUtil and Servlet I imported java.util.Date. If I use (as in exaomle above) myStmt.setDate(X, value) I've gopt an error: java.util.date cannot be converted into java.sql.date

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Luke_Nuke
  • 461
  • 2
  • 6
  • 23
  • 1
    FYI, the troublesome old `java.util.Date` and `java.sql.Date` classes are now legacy. Supplanted years ago by the *java.time* classes. Specifically, `Instant` and `LocalDate`, respectively. – Basil Bourque Jul 04 '18 at 00:08

2 Answers2

2

If you are using Java8+ and Jdbc 4.x you can use java.time API with setObject instead of java.util.Date, where you can also use LocalDateTime with your zone Id like so :

LocalDateTime startDate = ...
LocalDateTime endDate = ...
myStmt.setObject(4, startDate);
myStmt.setObject(5, endDate);

If you stick with Java 7 or less you can see this link :

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

You need to use a java.sql.Date:

myStmt.setDate(3, new java.sql.Date(theBook.getStart().getTime()));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • If I use java.sql.Date is it ok if on my Servlet and Java class java.util.Date remains? Is it ok if I import java.sqla.date only for DBUtil and use syntax as you showed me? :) – Luke_Nuke Jul 03 '18 at 20:57
  • 1
    @Luke_Nuke If you aren't using `java.util.Date` anywhere else in the same code, sure, you can just import `java.sql.Date`. – Mureinik Jul 03 '18 at 20:58
  • I am importing java.util.Date in my Class.java ServletController.java and ATM also in my DBUtil. So If I do import them (java.util) and i Use syntax: myStmt.setDate(3, new java.sql.Date(theBook.getStart().getTime())); should it be ok? Do I have ti import java.sql.Date for that syntaxt or it is not necessary then? :) – Luke_Nuke Jul 03 '18 at 21:01
  • 1
    @Luke_Nuke if you're using the fully qualified class name (`java.sql.Date`), you don't need to import it. – Mureinik Jul 03 '18 at 21:02