Insert a date into a MySQL database using PreparedStatement

I want to update a row date in a MySQL database using a prepared statement. I tried a lot and always got the java.util.Date cannot parse into java.sql.Date error or vice versa. I haven’t imported anything here. Import according to your answer.

 public class Date1 { public static void main(String args[]) { String source="2008/4/5"; SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); java.sql.Date d=(Date) format.parse(source); Class.forName("com.mysql.jdbc.Driver"); Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root"); PreparedStatement ps=con.prepareStatement("insert into ankur1 values(?)"); ps.setDate(1,(java.sql.Date) d); ps.executUpdate(); } } 
+4
source share
3 answers

Write it down

 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 pass java.util.Date to your subtype java.sql.Date . You have to convert it. Also note that your format string does not match your actual date format, as Bill Lizard commented.

+7
source

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

pstmt.setTimestamp (1, date);

Try it, it might work .. Thanks

+3
source

Here is another simple way to solve this problem:

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

Or can you replace "?" with real data.

This is how I insert the date and time in mySQL, I just understood.

We can configure the parameters to fit our data format, it’s easy and clean.

+1
source

Source: https://habr.com/ru/post/1440054/


All Articles