I have a Java MVC model.Which has timestamp as one of the DB value which is already inserted into DB.I have declared the data type as Timestamp in DB,Now the problem is If i try to retrieve it is showing null values & can not be represented as java.sql.Timestamp
Statement :
pstmt = con.prepareStatement("SELECT timestamp, FROM nid where id=?");
pstmt.setDouble(1, nidev);
rs = pstmt.executeQuery();
if(rs.next())
{
timeBean.setHbtimestamp(rs.getTimestamp("timestamp"));
}
Bean Class:
private Timestamp hbtimestamp;
public Timestamp getHbtimestamp() {
return hbtimestamp;
}
public void setHbtimestamp(Timestamp hbtimestamp) {
this.hbtimestamp = hbtimestamp;
}
MyDB value is successfully inserted :2015-05-14 15:45:57
output: Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp
Set in your MySQL
zeroDateTimeBehavior=convertToNull
Then empty time stamp values will be interpreted as NULLs
Well explained here
Related
I have an column defined as datetime(2) and I have to create a new date in this format - 2016-01-01T19:33:15-05:00
Entity: private Date transactionTime;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = null;
try {
date = formatter.parse(formatter.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
obj.transactionTime(date);
It is getting inserted in SQL as like this - "2021-08-26 14:19:09.0000000" but I need insert this in the format mentioned above.
There is only column type, datetimeoffset that can hold the timezone offset (e.g. -05:00 as mentioned in your question) value. Check the Data type mappings documentation to learn more about it.
So, if you want to store the timezone offset value, change the column type to datetimeoffset. After that, you will be able to insert the value which you have mentioned in the question.
You can use the following code to access the stored value:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT foo FROM mytable WHERE ...");
while (rs.next()) {
DateTimeOffset dateTimeOffset = rs.getObject(1, DateTimeOffset.class));
System.out.println(dateTimeOffset);
}
rs.close();
st.close();
where foo the name of the column of type, datetimeoffset.
I am using mysql 5.7.x version. Also i am using java 8. I am trying to insert java.time.instant current datetime in millisecond precision into my mysql database from java code. For that I am using preparedstatement.
The table in my database is:
CREATE TABLE `test_table` (
`id` INT NOT NULL AUTO_INCREMENT,
`timestamp` TIMESTAMP(3) NOT NULL,
PRIMARY KEY (`id`));
My java code to insert is:
Instant instant = Instant.now().truncatedTo(ChronoUnit.MILLIS);
try (Connection conn = DbConnection.getCon();
PreparedStatement ps = conn.prepareStatement("INSERT INTO test_table (timestamp) VALUES (?)");) {
ps.setTimestamp(1, Timestamp.from(instant));
ps.executeUpdate();
LOG.info("Instant: {} and long: {}", instant, instant.toEpochMilli());
} catch (SQLException ex) {
LOG.error(ex.getMessage());
}
From my log, I can see instant with milliesecond as: 2019-07-30T10:52:34.865Z.
But in my mysql database it becomes: 2019-07-30 10:52:34.000Z
I have searched so many questions and answers in stack but none seems to work for me.
Update 1:
I tried using setObject as:
ps.setObject(1, Timestamp.from(instant));
But still same result. Cannot retrieve the milliseconds in database.
MySQL has FROM_UNIXTIME() function that can take long values inside and returns a representation of the unix_timestamp in 'YYYY-MM-DD hh:mm:ss' or 'YYYYMMDDhhmmss.uuuuuu' format.
Reference from their manual here:
FROM_UNIXTIME()
Since I have milliseconds since epoch, thus I have to use
FROM_UNIXTIME(instant.toEpochMilli() * 0.001)
in my insert statement.
Yes nothing needs to be changed in database. The only things that are changed are in java code which are setObject() function used for preparedStatement, passing instant.toEpochMilli() as the argument there and finally use of FROM_UNIXTIME() function inside insert statement.
My final java code looks something like this:
Instant instant = Instant.now().truncatedTo(ChronoUnit.MILLIS);
try (Connection conn = DbConnection.getCon();
PreparedStatement ps = conn.prepareStatement("INSERT INTO test_table (timestamp) VALUES (FROM_UNIXTIME(?*0.001))");) {
ps.setObject(1, instant.toEpochMilli());
ps.executeUpdate();
LOG.info("Instant: {} and long: {}", instant, instant.toEpochMilli());
} catch (SQLException ex) {
LOG.error(ex.getMessage());
}
I have run into this weird Timestamp to Date Conversion issue in Oracle SQL.
Here is the SQL statement:
String INSERT_SQL = String.format("INSERT INTO AUDIT_TASK (%s, %s, %s, %s) VALUES (AUDIT_TASK_SEQ.nextval,?,?,?)",ID,CLASS_NAME,TASK_STEP_TIMESTAMP,OPERATOR);
java.util.Calendar utcCalendarInstance = Calendar.getInstance(TimeZone .getTimeZone("UTC"));
java.util.Calendar cal = Calendar.getInstance();
final PreparedStatement stmt = con.prepareStatement(INSERT_SQL);
stmt.setString(1, audit.getClassName().getValue());
// Save the timestamp in UTC
stmt.setTimestamp(2,new Timestamp(cal.getTimeInMillis()), utcCalendarInstance);
When I execute this statement, while most of the times the creation_date and task_step_timestamp dates are same, but sometimes I get the task_step_timestamp generated with some bogus dates- like '25-APR-0000' or '00-Jan-0001' etc.
ID | Creation_date | Task_step_timestamp
1 |27-APR-2018 17:58:53| 25-APR-0000 09:00:45
2 |27-APR-2018 18:06:25| 00-Jan-0001 09:18:25
The data type of task_step_timestamp column in Oracle DB is 'DATE'.
Can some one suggest the cause of this inconsistent conversion of timestamp to date?
I don't understand why you are using String#format here. Just use a regular insert which mentions explicit columns:
String INSERT_SQL = "INSERT INTO AUDIT_TASK (ID, ERROR_MESSAGE, TASK_STEP_TIMESTAMP, OPERATOR) ";
INSERT_SQL += "VALUES (AUDIT_TASK_SEQ.nextval, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(INSERT_SQL);
Then bind your values:
stmt.setString(1, audit.getErrorMessage() != null ? audit.getErrorMessage().getValue() : null);
stmt.setTimestamp(2, new Timestamp(cal.getTimeInMillis()), utcCalendarInstance);
stmt.setString(3, audit.getClassName().getValue());
Note carefully that the placeholders, in order from left to right, are for the error message, task step timestamp, and operator. Your original code appears to be binding the parameters out of order. By using an insert statement which explicitly mentions the columns, you may avoid this problem.
Edit:
It also doesn't make sense to me why you are worrying about time zones for your timestamp. Just get the numbers of milliseconds since the epoch, and then let the database store that as UTC:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
stmt.setTimestamp(2, timestamp);
I want to link the mysql database using Java, execute query returns the record of the specified period, and finally present the result in form of table in java.
How can I convert the input string into the mysql valid date and output the result?
I tried this, but failed.
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? and TransactionDate <= '"+t1+"' and id1=?);
ResultSet rs = query.executeQuery();
Thank you very much!!!
You have to set parameters to PreparedStatement instance as follows:
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? AND TransactionDate <= ? AND id1 = ?);
query.setDate(1,new java.sql.Date(t1.getTime()));
query.setDate(2,new java.sql.Date(t2.getTime()));
query.setLong(3,id);// Assuming Datatype of Id to Long and value in variable id, Change accordingly if not.
ResultSet rs = query.executeQuery();
Edit : Changed datatype of setDate from java.util.Date to java.sql.Date
I have a database where I have a field that is type DATE and I want to make a function in java to insert values in the database.
The problem is that when I insert a Date I get a NULL in the database DATE field.
I'm doing this:
PreparedStatement stmt = null:
stmt = conn.prepareStatement("INSERT INTO DB1(print_date) values(?)";
stmt.setDate(1, database.getPrintDate());
stmt.executeUpdate();
How can I insert the PrintDate which is DATE type in the database? Thank you