Inserting date into MySQL database using a PreparedStatement

旧巷老猫 提交于 2019-12-05 16:19:56

Write this

java.sql.Date d= new java.sql.Date(format.parse(source).getTime());

instead of this:

java.sql.Date d=(Date) format.parse(source);

Because you cannot just cast java.util.Date to its subtype java.sql.Date. You have to convert it. Do also note that your format string doesn't match your actual date format, as Bill the Lizard commented.

java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());

pstmt.setTimestamp(1, date);

Try this it may work.. Thanks

here is another simpler way to solve this:

preparedStatement = connect.prepareStatement("INSERT INTO test.TABLENAME VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)"); 

Or, you can replace the "?" with real data.

This is how I insert date and time to mySQL, just figured it out.

We can adjust the kinds of parameters to meet our data's format, it's easy and clean.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!