Retrieving MySQL time in java - java

I am running the following query to get time difference of two times
resultSet = statement.executeQuery("SELECT TIMEDIFF('14:03:55.256', '14:02:51.780') AS td");
MySQL gives time difference in this format
00:01:03.476
But both
resultSet.getTime("td"); and resultSet.getObject("td");
returns 00:01:03
According to the documentation getTime(String string) retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Time object in the Java programming language.
java.sql.Time corresponds to SQL TIME and contains information about hour, minutes, seconds and milliseconds.Then why am I getting 00:01:03 instead of 00:01:03:476?
What I basically want is to store 00:01:03.476 into a String. Is there any workaround or I am doing it wrong?

If you are verifying the result by printing it out note that java.sql.Time.toString() only returns a string in the format hh:mm:ss
You should really use rs.getTimestamp which will return a java.sql.Timestamp

Try to do this:
String s = new SimpleDateFormat("HH.mm.ss.SSS").format(t.getTime());
where t is your variable of type java.sql.Time.
Hope this will solve you problem.

Related

Could not save date field as ISO date in mongo db via Camel (Caused by: java.lang.IllegalArgumentException: Invalid BSON field name $date) [duplicate]

We are trying to insert a document with the current date as it's field. We are writing in java using eclipse plugin for mongodb. We want to execute the Date() command of mongo to get the date from mongo and not from java.
How can I execute this mongo query?
db.example.insert({"date":new Date()})
I found this question in a previews question but the answer was not helpful
Link
The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to "example"
Date now = new Date();
BasicDBObject timeNow = new BasicDBObject("date", now);
example.insert(timeNow);
If you are looking for a way to use the "server" time in operations, there is the $currentDate operator, but this works with "updates", so you would want an "upsert" operation:
BasicDBObject query = new BasicDBObect();
BasicDBObject update = new BasicDBObject("$currentDate",
new BasicDBObject("date", true)
);
example.update(query,update,true,false);
Since that actually is an update statement, you need to be careful that you are not actually matching any documents if you intend this to be an insert only. So it would be best to make sure your "query" contains unique information, such as a newly generated _id or something equally unique.
You can do it trying something like this:
db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});
Use this:
db.example.insert({"date":new Date(Date.now())});
There is a key difference I noted when using Date() as follows.
{ dateWhenCreated : Date() }
vs
{ dateWhenCreated : new Date() }
Notice the "new" keyword in the second usage. Whereas the first usage loads the data "as a string", the second one loads date as a field with date data type.
This might impact your sorting capability - dates stored as strings don't get sorted the same way as dates stored as dates.
Per the mongodb documentation here

java.sql.SQLException: ORA-01843: not a valid month (Working in SQL DEVELOPER and doesn't work in JAVA)

I have a table in database that contains the 'Date_transaction' column his type is varchar.
In my Code JAVA, I create a SQL query via several conditions.
When I debug in Eclipse the query generated is like this:
SELECT *
FROM Transaction where 1=1
AND (to_date(Date_transaction,'YYYY/MM/DD HH:MI:SS') between '16/01/01' and '16/02/29')
AND projet = 'Project name'
AND nomtranche = 'tranche name' AND voletctrl = 'volet name'
AND (numeroimmeuble BETWEEN 1 AND 100)
AND validation = 1
AND statutDocNormal = 'statut'
AND numeroAppartement = 14
order by DateTrasaction DESC;
I execute this query in SQL DEVELOPER, the query is executed successfully without any error.
But in my code Java I get this Error : java.sql.SQLException: ORA-01843: not a valid month.
When I want to generate the query, I use this method to convert my date, this I spend in parameter (In the query it's : 16/01/01 and 16/02/29):
public static String parseDate2(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
String dt = sdf.format(date);
return dt;
}
I try this answer but it's not working.
You are relying on the session's NLS_DATE_FORMAT, which is set differently in the client and probably indirectly via your Java locale. Use explicit conversion with a specific format mask:
... between to_date('16/01/01', 'RR/MM/DD') and to_date('16/02/29', 'RR/MM/DD') ...
But it would be better to use four-digit years and YYYY (remember Y2K?), or date literals - those those don't work with variable values.
This also looks wrong:
to_date(Date_transaction,'YYYY/MM/DD HH:MI:SS')
If `date_transaction is already a date then you are implicitly converting it to a string and then back to a date, which is pointless and dangerous. And then possibly back to a string to compare with your fixed values. If it is a string then it shouldn't be. Either way you need HH24 rather than just HH so you can distinguish between AM and PM.
If it is a date you need:
...
date_transaction between to_date('2016/01/01', 'YYYY/MM/DD')
and to_date('2016/02/29', 'YYYY/MM/DD')
...

Query using setDate does not find results - cannot see final-query with parameters

I have an SQL which looks into a dimension table (which stores every dates until year 2020) and then shall retrieve the todays row.
I watched into the table, todays date is in there.
The problem is, that SQL does not return any result.
I am thinking of a problem related to the use of java.sql.PreparedStatement.setDate method.
In past i think this was working fine, now I did some kine of regression test and it failed. The differences to the past are having Oracle 12 DB now instead of 11 in past and running it on CentOS 6.5 instead of AIX.
On search I found this topic here:
Using setDate in PreparedStatement
As far as I can see, I am doing as suggested.
Heres the java code and the query:
public static String SELECT_DATUM = "SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME, YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME WHERE DATE = :date";
java.util.Calendar now = Calendar.getInstance();
now.clear(Calendar.HOUR);
now.clear(Calendar.MINUTE);
now.clear(Calendar.SECOND);
now.clear(Calendar.MILLISECOND);
Date tmpDate = now.getTime();
Date tmpDate2 = new Date(((java.util.Date)tmpDate ).getTime());
statement.setDate(1, tmpDate2 );
I notice that getTime() is called twice. But I dont think its that bad.
I also noticed some displaying formats:
in Database the date-colums shows me the date like this: '08.11.2015'
in java while debugging tmpDate2 shows me a date like this: '2015-11-08'
in java while debugging tmpDate shows me a date like this 'Sun Nov 08 12:00:00 CET 2015'
But again, these are just display formattings while it is a dateobject in background and a date-type in database. I would expect that je JDBC driver would map this itself without formattings, that why we are using setDate method and not setString.
What am I doing wrong? What could I do for further debugging to get it?
I would like see the resulting SQL query which is finally executed with the parameter.
I tried this sql on db isntance:
SELECT * FROM v$sql s WHERE s.sql_text LIKE '%select time%' ;
but only getting this then: "... where date = trunc(:1 )"
On this row at least I can see that it was using the right schema I expected it to use and where I checked whether todays date is available.
Edit:
something I found out:
I saw another code using the same function but giving an GregorianCalendar instead Calendar. When using
new GregorienCalandar();
instead of
Calendar.getInstance();
Theres no difference.
But when I assign a date and dont let the system take the current time, then it works:
Using
new GregorianCalendar(2015, Calendar.NOVEMBER, 8);
Would retrieve the row I want from SQL.
Zsigmond Lőrinczy posted this answer as comment:
Try this: SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME,
YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME
WHERE DATE = TRUNC (:date) – 3 hours ago
This works for my problem.
I am writing this as reponse to check it later as answer on this question if hes not going to write his own response (to get the reputation-points).
But I am wondering how I could get the same by preparing on java.
The code uses the clear-methods, which where released into an own method named 'trunc'. I think the programmer intendet to do this instead of TRUNC in SQL. I am wondering if it werent possible to do so in java and if yes, how?
Edit:
And I am wondering why a TRUNC is needed at all. Because the column in Database is of type Date an not Timestampt. So wouldnt there be an automatically trunc? I would expect this. Why do I need a trunc on SQL?

Retrieving data from database using JDateChooser?

I want to retrieve only data that have same date_Add and output it to the table_patients
Here is the code
private void btn_GoActionPerformed(java.awt.event.ActionEvent evt) {
java.util.Date chooser= choose.getDate();
java.sql.Date sqlchooser=new java.sql.Date(chooser.getDate());
try{
String sql="select * from Patients_Details where Date_Add='"+sqlchooser+"'";
pst=conn.prepareStatement(sql);
pst.setDate(1,sqlchooser);
rs=pst.executeQuery();
table_patients.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException sql)
{ sql.printStackTrace(); }
}
but i get this error
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at org.sqlite.PrepStmt.batch(PrepStmt.java:192)
at org.sqlite.PrepStmt.setObject(PrepStmt.java:245)
at org.sqlite.PrepStmt.setDate(PrepStmt.java:290)
at employeeJFrame.btn_GoActionPerformed(employeeJFrame.java:981)
at employeeJFrame.access$1300(employeeJFrame.java:18)
at employeeJFrame$13.actionPerformed(employeeJFrame.java:391)
error points to this line
pst.setDate(1,sqlchooser);
Could someone please help? NB: I am a java begginer
There are a number of issues here.
You're passing the day of month to a constructor that expects a milliseconds time value. This will result in your sqlchooser date being 1 to 31 milliseconds after midnight on 1970-01-01. If you look at the documentation, you'll see that java.util.Date.getDate()
Returns the day of the month represented by this Date object...
And the constructor java.sql.Date(long)
Constructs a Date object using the given milliseconds time value...
Also be aware that java.util.Date.getDate() is deprecated in favor of Calendar.get(Calendar.DAY_OF_MONTH).
You're setting the date condition explicitly by constructing the SQL string with sqlchooser and are then attempting to set the date as parameter of the prepared statement (but the statement has no parameters). You only need to do one of these. Read to Using Prepared Statements to understand how parameters work.
The first issue will likely result in you receiving no results. The second issue should be causing an SQLException. Neither of these should cause any problem on the line you indicated, but I'd suggesting fixing these problems and moving on from there.
For work with dates going forward, you should consider using Joda Time rather than the base Java date/time API, which many regard as poorly designed.
UPDATE (post provision of exception details)
Post your edit, it's clear that you are receiving this error because you are trying to assign a parameter to a prepared statement that has no parameters (point 2 above). Parameters are represented by the '?' character in statements. See the linked documentation above for details.
If you look at the exception, you'll see it occurs in the org.sqlite.PrepStmt.batch method. The source of this method is:
private void batch(int pos, Object value) throws SQLException {
checkOpen();
if (batch == null) batch = new Object[paramCount];
batch[batchPos + pos - 1] = value;
}
For your statement, paramCount==0, so the batch Object array is created with length 0. The last line then attempts to set the first element (0 + 1 - 1 = 0) to your passed Date object, which is why you get an ArrayIndexOutOfBoundsException.
Bottom line: Read and understand about prepared statement parameters at the link provided.

java mysql select statement not returning full date

I'm a java newbie but I'm not sure what I'm doing wrong. When I try to retrieve the last two dates from a database it only displays the year(while in mysql the same command provides the correct result).
Mysql command: SELECT DISTINCT date From fundanalysis ORDER BY date DESC LIMIT 2
Expected result:
2011-06-13
2011-06-08
Here's my java code:
preparedStatement = con.prepareStatement("SELECT DISTINCT date From fundanalysis ORDER BY date DESC LIMIT 2");
ResultSet numberofrowsresultset = preparedStatement.executeQuery();
numberofrowsresultset.next();
// most recent date
currentdate.add(numberofrowsresultset.getInt("date"));
System.out.print(numberofrowsresultset.getInt("date"));
numberofrowsresultset.next();
// last date before most recent
currentdate.add(numberofrowsresultset.getInt("date"));
return currentdate;
The final result is: [2011, 2011]
I basically want the exact same result as I get when I run the mysql query because I have to submit it as is to do another query later in the program.
pls help!
it is .getDate not .getInt
try:
numberofrowsresultset.getDate("date");
Try use .getDate() instead of .getInt():
currentdate.add(numberofrowsresultset.getDate("date"));
You are using .getInt which returns a numerical value. You need to use .getDate instead when you are getting a date value:
System.out.print(numberofrowsresultset.getDate("date"));
^^^^ change Int to Date
Date is not an integer so your '.getInt("date")' method is not returning the result you expect.
You need
java.sql.Date myDate = numberofrowsresultset.getDate("date");

Categories