Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(JAVA) Need to convert DATE to prepared statement for SQL

I have been looking and trying solutions provided on the web (and SO) for the last hour on how to use the Date type in Java but I can't seem to get it working. I am using NetBeans 11.2 and I am not used to Java and it is giving me a hard time (no pun intended). It seems that LocalDateTime, Date and Time are deprecated and that I should be using java.time.

To be honest, I don't know what to do anymore. I am trying to build a query with inputs value to save in mySQL database.

The source of the Date is from <input type="date">

SignIn.java (servlet) :

String birthDate = request.getParameter("data_birthdate");
        
UserDto userDto = null;
UserDao userDao = new UserDao(); 
        
try 
{ 
// Tried this 
    userDto = userDao.CreateUser(LocalDateTime.parse(birthDate));
// Tried that
    userDto = userDao.CreateUser(Date.parse(birthDate));
// Tried this 
    userDto = userDao.CreateUser(Time.parse(birthDate));
}

userDao.java (Dao) :

public void CreateUser(Date dateBirth) throws SQLException {
try {
        connect = db.getConnect();
        ps = connect.prepareStatement(SQL_CreateUser);
        ps.setDate(1, dateBirth);
        ps.executeUpdate();
    }
}
like image 833
pensum Avatar asked Jun 19 '26 19:06

pensum


1 Answers

You may use LocalDateTime along with PreparedStatement#setTimestamp(). Here is roughly how you would do that:

String birthDate = request.getParameter("data_birthdate");
// assuming your text birthdates look like 1980-12-30 00:30:05
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dt = LocalDateTime.parse(birthDate, formatter);

try {
    connect = db.getConnect();
    ps = connect.prepareStatement(SQL_CreateUser);
    ps.setTimestamp(3, Timestamp.valueOf(dt));
}
catch (Exception e) {
    // handle exception
}

Note carefully the format mask being used in the call to DateTimeFormatter#ofPattern. You need to replace that with whatever mask actually fits your string dates.

like image 191
Tim Biegeleisen Avatar answered Jun 21 '26 07:06

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!