Insert data into a database using java

I want to insert datetime into a MySql database using Java and a prepared statement:

Calendar cal = Calendar.getInstance(); PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " + "(Time) VALUE (?) "); stmnt.setDate(1, new java.sql.Date(cal.getTime())); stmnt.executeQuery(); 

NOTE: there is currently an error - not finding line (java.sql.Date) 4 here

db is an instance of a wrapper class class that provides what I need from java.sql - it's just getting the prepared statement from my connection object here.

The time (column) is the date in my database, and I can only see the setDate and setTime methods, but I want to save both - also my code does not work anyway; -)

If someone could give me some pointers to insert a combined date time (current time would be a big help as my first goal) in the MySql database using the prepared expression, I would be very grateful.

thanks

+4
source share
2 answers

The constructor for java.sql.Date takes a lot (milliseconds since 1970) java.sql.Date To get milliseconds from java.uitl.Calendar, you use cal.getTimeInMillis()

Your code will look like this:

 Calendar cal = Calendar.getInstance(); PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " + "(Time) VALUE (?) "); stmnt.setDate(1, new java.sql.Date(cal.getTimeInMillis())); stmnt.executeQuery(); 
+5
source

The following code should allow you to insert a date accurate to milliseconds. I used it with HSQLDB, Sybase, SQL Server and MySql without any problems.

 java.util.Date date = getMyDate(); if (date == null) { statement.setNull(insertionIndex, Types.TIMESTAMP); } else { statement.setTimestamp(insertionIndex, new Timestamp (date.getTime())); } 
+2
source

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


All Articles