java.sql.Timestamp to Date Conversion in Oracle SQL - java

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);

Related

How to insert a row into database?

I have written this code to add stuff to the database, however, when I try running it it does not work, i've been looking for ways to do it, but i just cant seem to find the solution, can anyone help?
String mySQL ="INSERT INTO Measurement (Level, Time, Date, TankID)"+"VALUES (textField1, currentTime,currentDate,(SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
stmt.executeUpdate(mySQL);
Both your SQL and prepared statement are malformed. Try using an INSERT INTO ... SELECT here:
String sql = "INSERT INTO Measurement (Level, Time, Date, TankID) ";
sql += "SELECT ?, ?, ?, TankID ";
sql += "FROM Tanks ";
sql += "WHERE TankName = '2' AND Site_ID = '1'";
stmt.setString(1, textField1);
stmt.setString(2, currentTime); // not sure about the type here
stmt.setString(3, currentDate); // also not sure about the type
stmt.executeUpdate();
Note that I am unsure about both the Java and SQL binding types of the columns for currentTime and currentDate. If not string, then the above would have to change slightly.
You should be using PreparedStatement to properly set the first parameter of the insert query and check the documentation of your DB server to use existing functions to get current time and date.
For example, mySQL has functions CURDATE() and CURTIME()
String query = "INSERT INTO Measurement (Level, Time, Date, TankID) "
+ "VALUES (?, CURTIME(), CURDATE(), (SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, textField1); // could be textField1.getText() or textField1.getValue()
statement.executeUpdate();
}
Based on your Database type change the connection details
Follow this Link for creating JDBC Connection and Inserting data
If you did the above steps please ignore this..

java sql - insert timestamp into sql database

I'm trying to insert a timestamp into a database, but my code throws an exception, which tells me it's something with my sql statement.
The exception message shown is:
"Fout in Rit_ToevoegenController.okKnop(): SQLException in RitDB.voegRitToe() - statement"
okKnop is a different method that calls voegRitToe().
The type of the column called 'starttijd' is TIMESTAMP, and the DB Data type is DateTime.
i'm fairly certain that it's the timestamp that causes problems, because the other 2 are just a String and an int.
Any help with making it work would be greatly appreciated. I need to insert both the time and date into the database for comparing later.
public void voegRitToe(Rit r) throws DBException{
Timestamp starttijd = new Timestamp(System.currentTimeMillis());
//Date date = new Date(starttijd.getTime());
try(Connection conn = ConnectionManager.getConnection();){
try(PreparedStatement stmt = conn.prepareStatement("insert into rit(starttijd, lid_rijksregisternummer, fiets_registratienummer) values(?,?,?)");){
stmt.setTimestamp(1, starttijd);
stmt.setString(2, r.getLid().getRegisterNr());
stmt.setInt(3, r.getFiets().getRegisNr());
stmt.execute();
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - statement");
}
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - verbinding");
}
}
TIMESTAMP and DATETIME serve different purposes; TIMESTAMP is for automatic time stamping.
java.util.Date starttijd = new java.util.Date(System.currentTimeMillis());
java.util.Date starttijd = new java.util.Date(); // Or this
I guess you came at Timestamp, as java.sql.Date wraps java.util.Date by setting the time part to zero!
If the database server's time is correct, one could also do:
... VALUES(NOW(), ?, ?)
By the way, java 8 introduces new date/time classes and "improve" upon the JDBC usage, if you have a java 8 compliant driver.

How do i correctly enter a Decimal Type through JDBC?

I've connected a java project (using netbeans) to a MySQL database, but I'm having trouble inserting data.
If i use this code it inserts just fine:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('milk', 3.18, '2015-01-23','Grocery');";
but when i try and replace the insert values with these predefined values:
String ExpenseName;
Double ExpenseCost;
String ExpenseDate;
String ExpenseType;
and then use this code to insert the values:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('"+ExpenseName+"',"+ExpenseCost+",'"+ExpenseDate+"','"+ExpenseType+"');";
I get the error: SQLException: Column 'Cost' cannot be null
my cost field in my database is defined as decimal(15,2)
Even more annoyingly, when i try and use this code to update as a test:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('"+ExpenseName+"',3.18,'"+ExpenseDate+"','"+ExpenseType+"');";
i get another error saying:
SQLException: Data truncation: Incorrect date value: 'null' for column 'Purchase_Date' at row 1
this is confuses me a lot because through the database i have no issues with updating the Purchase_Date field in the expenses table with a '2015-01-23'. if its of any use that field is of type date. perhaps it's because the date object in my java is string?
You really should use a PreparedStatement
PreparedStatement pst= con.prepareStatement(
"insert into expenses(Expense,Cost,Purchase_Date,Description)" +
" values(?, ?, ?,?)");
pst.setString(1, ExpenseName);
pst.setDouble(2, ExpenseCost);
pst.setDate(3, new java.sql.Date(ExpenseDate.getTime()));
pst.setString(4, ExpenseType);
pst.executeUpdate();
Also, you should inititalize your variables properly.
Assuming that they are declared as fields, you should initialize them as :
String ExpenseName="SomeName";
Double ExpenseCost=1.8;
Date ExpenseDate=new Date();
String ExpenseType="Some Type";
Uninitialized variables could be the source of the SQLException, because ExpenseName and ExpenseDate would be concatenated as "null" in your SQL string.
You should always use a PreparedStatement to insert/ update data and not use String concatenation. This will not only help you with formatting the data correctly but also protect you against SQL injection attacks.

Searching between 2 date

Have a problem search between 2 date
my sql statement in java
String sql ="Select * from Payment where Payment_Date between '"+date_1+"' and '"+date_2+"'";
It give me data type mismatch, I guess my problem occur in '"+date_1+"' and '"+date_2+"' ??
date_1 and date_2 I get from
Date date_1 = date1.getDate();
Date date_2 = date2.getDate();
Start using a PreparedStatement , it will prevent SQL injections . Read this SO Q&A for more.
You can do something like this :
String sql ="Select * from Payment where Payment_Date between ? and ? ";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setDate(1, date_1 );
pstmt.setDate(2, date_2 );
// date_1 and date_2 objects should be of type java.sql.Date
Make sure you set the correct parameter types in the setXXX() methods. Remember if the data type for Payment_Date is DATE and related types, you need to set java.sql.Date in the setDate() method. If the data type of column is TIMESTAMP, then use java.sql.Timestamp and setTimestamp() method.
Footnote :-
If you have a java.util.Date object with you , you can convert that to java.sql.Date as :
java.sql.Date sqlDateObject = new java.sql.Date(utilDateObject.getTime());
Package of Date class must be java.sql not java.util.
pstmt = conn.prepareStatement("Select * from Payment where Payment_Date between ? and ?");
pstmt.setDate(1, date_1);
pstmt.setDate(2, date_2);

Insert Date field into DB

I am having a textbox field in my jsp called "req_date". The user is selecting a date from a javascript calendar in the format of "DD-MON-YY" ex. "29-aug-2010".So, now I am stuck while trying to insert it in the DB.
I tried " String queryString = "INSERT INTO Charity (req_date) VALUES (?)", but it is not inserting. How do I solve tis out.
The req_date is type of date in the DB.
Can you please help
Date format depends upon Database you use.
For reference Date formats with Oracle.
so your query should look like :
String queryString = "INSERT INTO Charity (req_date) VALUES (to_date('29-aug-2010', 'dd-mon-yyyy'))"
This is just to answer your question. But I will prefer usage of PreparedStatement as also suggested in other answers.
Your code using PreparedStatement should look something like following: (NOTE: I have not tested this code )
String formatIn = "dd-MMM-yyyy";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-Aug-2010");
java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());
PreparedStatement prest = con
.prepareStatement("INSERT INTO Charity (req_date) VALUES (?)");
prest.setDate(1, sqlDate);
int row = prest.executeUpdate();
Use a PreparedStatement and its setDate(..). Or use a timestamp (long).
It depends on your database, PostgreSQL does recognize this format:
SELECT CAST('29-aug-2010' AS date);
Result:
'2010-08-29'
In most cases, you'd better use the ISO-format yyyy-mm-dd.

Categories

Resources