Trouble when inserting time and date to db using Java - java

Here's my code:
uprs.moveToInsertRow();
uprs.updateString("Sender", myName);
uprs.updateString("Receiver", withWho);
uprs.updateString("Message", myMessage);
//uprs.updateString("Time",****);
uprs.insertRow();
Things go perfectly when adding the non-time data into the database.
But I am struggling how to add the current date and time into the database.(Ms SQL 2008)
Is there any expert can tell me how to organize the code about getting the current time and date and insert them into the db?
The data type of Time in my db is "datetime".
Thank you!

For a date/time type you should use updateTimestamp instead of updateString

Related

Converting java.util.Date to Java.sql.Date using Javalin

I am creating a web app using Java (Javalin and Maven) for university.
We have to make a website for movie bookings and I am struggling to find out how to properly convert dates so that they are readable by SQL and Java.
I have to store date values in a database and to this point I have just been storing them as a string but I want it to have a more specific date meaning. It is built using the MVC model.
This is the code in my sessions model.
public void setSessionDate(Date sessionDate) {
java.sql.Date date = new java.sql.Date(sessionDate.getTime() );
this.sessionDate = sessionDate;
That is the code in my SessionsDao file.
stm.setDate(3, new java.sql.Date(sessions.getSessionDate().getTime()));
And finally this is the code in my SQL create field.
sessionDate DATE not null,
When I try to create a new movie session this is the error the console prints.
[qtp198903030-30] WARN io.javalin.Javalin - Uncaught exception
io.javalin.core.validation.MissingConverterException: Can't convert to Date. Register a converter using JavalinValidation#register.
at io.javalin.core.validation.Validator$Companion.create(Validator.kt:35)
I am unsure how to convert the date properties correctly.
Any help or other methods on how to proceed would be greatly helpful!

How to delete from database with LIKE operator and context variable MySQL in Talend

I have a database that has the date as String and I have to delete the rows that have the same data in the csv file as in the database. More exactly, my dates look like this 2018-03-31T23:30:24+00:00. I want that when it gets a date like this, to delete from database where data LIKE %2018-03-31%, so it will delete all the records from that day, even if the time is not the same.
I have a job where tFileInputDelimited is connected with a tSortRow and then to tFlowToIterate. After that, I have a tJava where I extract the date and then a tMysqlInput where the query has the where clause like this: WHERE purchase_date LIKE '%"+context.date+"%' . Then, with a run if connection, I have tMysqlRow in which I have the delete statement with the same where clause. After that, of course, I have the tMysqlCommit.
The context.date is made like this:
context.dataaa=(String)globalMap.get("row6.purchase_date");
context.month=context.dataaa.substring(5,7);
context.year=context.dataaa.substring(0,4);
context.day=context.dataaa.substring(8,10);
context.date=context.year+"-"+context.month+"-"+context.day;
The problem is that, it doesn't delete from database. I want it to go row by row and delete all my records that have the same day in the csv and database.
The problem was from an if statement that compared the full date separately, so I had to compare only the day not day,year and month.
In Talend, you can define the pattern of a Date column to some usage.
Here, I have a tFileInputDelimited with a column date :
Column: date
Type : Date
pattern : "yyyy-MM-dd'T'hh:mm:ss"
That let me read a file with a value like 2018-03-31T23:30:24 because here, the pattern is used to "parse" the String from the file into a Date. Now if we add a LogRow and update the schema of this component, we can define a different pattern to format the Date
Column: date
Type : Date
pattern : "yyyy-MM-dd"
Input : 2018-03-31T23:30:24
Output : 2018-03-31
Know, if you don't want to play with the Schema, you can convert/format a date into a String with TalendDate.formatDate("yyyy-MM-dd", row1.date)

How to get Date AND Time from Oracle database, using Hibernate?

I have been given some code to work on. I need to modify the existing code to return an extra column. Using the tool, SQLDeveloper, I can see an example record (notice Date AND Time information is present):
30-NOV-17 15:54:00
The code that I have been given to work on does the following:
// Create a Hibernate query (Oracle SQL query)
Query query = session.createSQLQuery(<NATIVE_SQL_QUERY_HERE>);
List<Object[]> rawDataRows = query.list();
if (rawDataRows != null) {
for(Object[] rawDataRow : rawDataRows) {
// I am trying to get the Date AND Time here
Timestamp ts = (Timestamp) rawDataRow[7];
}
}
The problem is that I get an error when I try this approach (Cannot cast java.sql.Date to Timestamp).
When I access the data without the cast (just get the data in a Date object), I DO NOT get the Time information. And I need to have BOTH.
So far, nothing I have tried has worked - other posts have similar issues, but they are not quite the same.
Any advice/suggestions much appreciated - THANKS!
You can use this code:
....
Calendar calendar = Calendar.getInstance();
calendar.setTime(rawDataRow[7]);
Timestamp ts = new Timestamp(calendar.getTimeInMillis());
...

Database timestamps not matching

I have an action in struts2 that will query the database for an object and then copy it with a few changes. Then, it needs to retrieve the new objectID from the copy and create a file called objectID.txt.
Here is relevant the code:
Action Class:
ObjectVO objectVOcopy = objectService.searchObjects(objectId);
//Set the ID to 0 so a new row is added, instead of the current one being updated
objectVOcopy.setObjectId(0);
Date today = new Date();
Timestamp currentTime = new Timestamp(today.getTime());
objectVOcopy.setTimeStamp(currentTime);
//Add copy to database
objectService.addObject(objectVOcopy);
//Get the copy object's ID from the database
int newObjectId = objectService.findObjectId(currentTime);
File inboxFile = new File(parentDirectory.getParent()+"\\folder1\\folder2\\"+newObjectId+".txt");
ObjectDAO
//Retrieve identifying ID of copy object from database
List<ObjectVO> object = getHibernateTemplate().find("from ObjectVO where timeStamp = ?", currentTime);
return object.get(0).getObjectId();
The problem is that more often than not, the ObjectDAO search method will not return anything. When debugging I've noticed that the Timestamp currentTime passed to it is usually about 1-2ms off the value in the database. I have worked around this bug changing the hibernate query to search for objects with a timestamp within 3ms of the one passed, but I'm not sure where this discrepancy is coming from. I'm not recalculating the currentTime; I'm using the same one to retrieve from the database as I am to write to the database. I'm also worried that when I deploy this to another server the discrepancy might be greater. Other than the objectID, this is the only unique identifier so I need to use it to get the copy object.
Does anyone know why this is occuring and is there a better work around than just searching through a range? I'm using Microsoft SQL Server 2008 R2 btw.
Thanks.
Precision in SQL Server's DATETIME data type does not precisely match what you can generate in other languages. SQL Server rounds to the nearest 0.003 - this is why you can say:
DECLARE #d DATETIME = '20120821 23:59:59.997';
SELECT #d;
Result:
2012-08-21 23:59:59.997
Then try:
DECLARE #d DATETIME = '20120821 23:59:59.999';
SELECT #d;
Result:
2012-08-22 00:00:00.000
Since you are using SQL Server 2008 R2, you should make sure to use the DATETIME2 data type instead of DATETIME.
That said, #RedFilter makes a good point - why are you relying on the time stamp when you can use the generated ID instead?
This feels wrong.
Other than the objectID, this is the only unique identifier
Databases have the concept of a unique identifier for a reason. You should really use that to retrieve an instance of your object.
You can use the get method on the Hibernate session and take advantage of the session and second level caches as well.
With your approach you execute a query everytime you retrieve your object.

Query gives different output on different OS

I have written the following function in Java. This function returns current timestamp by executing a query. The function code is as follows :
private String getTimeStamp(){
String timeStamp=null;
try{
String strQuery="select current_timestamp";
PreparedStatement pmtQuery=con.prepareStatement(strQuery);
ResultSet rsQuery=pmtQuery.executeQuery();
rsQuery.next();
timeStamp=rsQuery.getString(1);
JOptionPane.showMessageDialog(null, "Value of timeStamp : "+timeStamp);
}catch(SQLException e){
System.out.println("SQL Exception in the getTimeStamp()");
}
return timeStamp;
}
When I use this function on windows It gives proper out put and works fine.
Ex.
If execute above function in widows it gives timestamp like ex. 2011-06-01 17:05:03
but when I execute this function in Debina linux it gives timestamp as
2011-06-01 17:05:03.0
It appends .0 to timestamp
Please guide me in this problem
1.why such different output comes on different system?
2.How to avoid this problem?
3.How to solve this problem?
I am using following configurations
windows
windows 7, Mysql database, Java 6
Linux
Debian linux, Mysql Database, Java 6
Thank You!
Use this
SELECT DATE_FORMAT(CURDATE(), '%d/%m/%Y %hh%mm%ss')
Note:
I wonder why you are querying to get the currentDate
The problem probably are different (default) settings of the JDBC drivers.
I would prefer fetching the timestamp as a Timestamp (subclass of java.util.Date):
import java.sql.Timestamp;
...
Timestamp timeStamp;
...
timeStamp = rsQuery.getTimestamp(1);
This way you can control how to format it in the Java code as/if needed (e.g. using SimpleDateFormat or String.format).
It's not portable, but you can use the DATE_FORMAT function:
SELECT DATE_FORMAT(CURRENT_TIMESTAMP, '%d/%m/%Y %h:%i:%s');
Documentation is here
you can also use
SimpleDateFormat
Its a simple date formatter.

Categories

Resources