Oracle Date Literal [DD-MON-RR HH.MI.SSXFF AM] - java

I'm trying to use the timestamp format [DD-MON-RR HH.MI.SSXFF AM] to insert my date.
I can't modify the database settings in anyway possible, and I have to insert the date through a JAVA's string format (I can't modify the class that defined it either).
Having said that, I need to literally reconstruct the format string-by-string without tempering the other class/db.
The nls settings for date is DD-MON-RR. 12-JUN-2012 and 12/JUN/2012 worked perfectly fine.
But I find it difficult to recreate the timestamp part of the date.
Listed below is a few format I've tried.
'12-JAN-12' < success
'12/JAN/2012' < success
'12/JAN/2012 10.30.25.000 AM < failed
'12/JAN/2012 10:30:25.000 AM < failed
Did messed up the : or .? Or was the zero(s) aren't enough for miliseconds? Been in this trouble for hours now.
Thanks in advance.
EDIT
After a few reasoning sessions, the seniors gave their permission to alter the model class. Everything's good now. Thanks for the help and suggestions.

Since you must send a string to the DB, you must rely on the implicit conversion of the oracle DB to the DATE type.
Since you can't change the DB settings, the only thing I can suggest is changing the session settings.
So, if you can run commands against the DB, try:
Statement st = conn.createStatement();
st.execute("alter session set NLS_DATE_FORMAT='dd/mm/yyyy hh24:mi:ss'");
(or some other format (it's not recomended to use mon in your format because it might involve NLS_TERRITORY too))

Related

How to change time zone in xml audit file (Oracle 11g)?

i'm working on a project in java to display everything what happend in my Oracle 11g Database. For this i started using the Audit Trail in XML format because i want to use it in my network.
I created a user for example to try this out. But my Problem is the wrong timestamp in the xml files and i would need it to check the time of connections etc.
<?xml version="1.0" encoding="UTF-8"?>
<Audit xmlns="http://xmlns.oracle.com/oracleas/schema/dbserver_audittrail- 11_2.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/oracleas/schema/dbserver_audittrail-11_2.xsd">
<Version>11.2</Version>
<AuditRecord><Audit_Type>1</Audit_Type><Session_Id>1260546</Session_Id><StatementId>1</StatementId><EntryId>1</EntryId><Extended_Timestamp>2016-10-01T15:59:47.473000Z</Extended_Timestamp><DB_User>CC</DB_User><OS_User>Admin-PC\Admin</OS_User><Userhost>WORKGROUP\ADMIN-PC</Userhost><OS_Process>1780:2512</OS_Process><Terminal>ADMIN-PC</Terminal><Instance_Number>0</Instance_Number><Action>100</Action><TransactionId>0000000000000000</TransactionId><Returncode>0</Returncode><Comment_Text>Authenticated by: DATABASE</Comment_Text><Priv_Used>5</Priv_Used><DBID>1434098587</DBID>
</AuditRecord>
<AuditRecord><Audit_Type>1</Audit_Type><Session_Id>1260546</Session_Id><EntryId>2</EntryId><Extended_Timestamp>2016-10-01T15:59:50.798000Z</Extended_Timestamp><DB_User>CC</DB_User><OS_User>Admin-PC\Admin</OS_User><Userhost>WORKGROUP\ADMIN-PC</Userhost><Terminal>ADMIN-PC</Terminal><Instance_Number>0</Instance_Number><Action>101</Action><Returncode>0</Returncode><DBID>1434098587</DBID>
</AuditRecord>
</Audit>
The Timestamp here is set at 15:59 but in my timezone it should be 17:59 (UTC+01:00). Then i tried this statement to check the timezone and curiously it was the right time.
SELECT db_user, extended_timestamp, action FROM v$xml_audit_trail WHERE db_user='CC' ORDER BY extended_timestamp DESC;
DB_USER EXTENDED_TIMESTAMP ACTION
CC 01.10.16 17:59:50,798000 +02:00 101
Do anyone know how to set the right timezone for the xml format?
Thanks in advance!
According to the documentation:
Extended_Timestamp indicates the time of the audited operation (timestamp of user login for entries created by AUDIT SESSION), in Coordinated Universal Time (UTC) or Greenwich Mean Time (GMT). This field only appears in the XML audit files, not the OS text audit files.
There doesn't seem to be anyway to change that, unless you transform the XML in the file later.
The timestamp is correct, it's just always in UTC. Whatever is going to consume this XML (you said you want to use it 'in your network') should be able to recognise that, and convert to other time zones if needed, but doing everything in UTC can be simpler anyway.
As an alternative you could generate your own XML from the v$xml_audit table with the data in whatever format(and timezone) you want, using the built-in XML generation tools (such as dbms_xmlgen).

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?

Java Retrieve date records in correct format from mysql

I have a table which was populated by a excel. The date in the columns shows according to my system's timezone when a select query is run in mysql.
But when i run the same query in java using jdbc connection, i am not getting the correct values as which was present in the excel.
I know it is a issue with the timezone. Please guide me with the changes that need to be done for the select query
Result of the following queries are NULL.
SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;
Just to elaborate on the issue, when i run a select query on date in mysql server, i get the right date values for a column. But when i run the same through a java program, i get converted values to a different timezone.
THe java code is as follows:-
resultList=(List<FosProd>)getEntityManager().createNativeQuery("select fe, count(ldcfe) as Ttlv, count(IF(ldcfe='PTP',1,NULL)) as PTP,DAY(ludfe) as dayte from (select FOS_NAME as fe,Last_Disposition_Code_FOS as ldcfe,Last_Updated_Date_FOS as ludfe from kic.master_mis group by ALLOCATION_DATE,ALLOCATION_BUCKET,BILLED_ID,CUSTOMER_NAME,TOTAL_OUTSTANDING) as s1 where monthname(ludfe)=\"NOVEMBER\" GROUP BY MONTH(ludfe), DAY(ludfe),fe;", FosProd.class).getResultList();
DAY function in SELECT is providing me converted values.
Please help.
public class FosProd implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Size(max = 50)
#Column(name = "fe")
private String fe;
#Basic(optional = false)
#NotNull
#Column(name = "Ttlv")
private long ttlv;
#Basic(optional = false)
#NotNull
#Column(name = "PTP")
#Id
private long ptp;
#Column(name = "dayte")
private Integer dayte;
Likely, it's the JDBC driver "helping" you out, altering the DATETIME/TIMESTAMP values because it's making adjustments to those values because of a difference in the timezone setting of the MySQL server and the JVM.
To see the timezone in effect for your connection to the MySQL server:
SELECT ##time_zone
Compare that to the timezone used by the JVM. If those are the same, then the JDBC driver shouldn't be making any adjustments to the values. If those are different, then it's likely that the JDBC driver is making timezone adjustments to the values.
Change JDBC Connection settings
We had to configure some options on the JDBC connection (MySQL J/Connector) url to stop the JDBC driver from doing brain dead timezone conversions, I think the most important change we made was:
useLegacyDatetimeCode=false
I think we also had to set noTimezoneConversionForDateType=true so timezone adjustments were't made on pure DATE datatypes.
I believe we also did some experimentation with custom mappings, between SQL datatypes and JDBC datatypes. But I don't think those ended up as part of our solution.)
(And obviously, this won't apply if you are using the MariaDB JDBC driver; we're just guessing that you're using MySQL J/Connector.)
NOTE: I'm not saying this is a solution to the issue being reported. The problem description provided in the question is very vague. There's no possible way for anyone to recommend a "solution" based on the information in the question.
Other approaches
That's not the only approach to addressing the issue, there are several other avenuesl suitability of these approaches really depends on your requirements, and what you are trying to achieve.
One "easy" button (probably not the most appropriate solution for you) would be to modify the timezone of the JVM to match the timezone of the MySQL server. BUT... that's going to impact a whole boatload more than just timezone adjustments made by JDBC Driver.
Another "patch" would be to not return DATETIME or TIMESTAMP expressions in the SELECT, but return expressions that have a character datatype instead. That will make the JDBC driver "bypass" any timezone adjustments is doing on DATETIME, (BUT... you'll be returning values that will be mapped into String, not Date or Calendar objects. e.g.
SELECT DATE_FORMAT(mydatecol,'%Y-%m-%d %h:%i:%s') AS mydate_string
FROM
In a similar vein, you could return the UNIX_TIMESTAMP(mydatecol), and that's going to return an integer (number of seconds since midnight Jan 1, 1970 UTC). The value return by that is going to be informed by the setting of the time_zone variable in the MySQL session.)
Again, that's likely not the most appropriate solution.
We assume that you are seeing the "correct" DATETIME values when you run a query against the MySQL server. What's most important here is knowing the setting of the time_zone variable in your MySQL session.
SELECT ##time_zone

lotus notes search by date with Java api

I'm trying to select records by date from a Lotus Notes database and have run into trouble with correctly formatting the date.
Here's the relevant code:
public void runNotes() {
Session s;
try {
s = NotesFactory.createSession((String)null, (String)null, "mypassword");
Database hkDB =
s.getDatabase("NBHDH001/YNM", "H\\DHH00001.nsf", false);
DocumentCollection docs = hkDB.search("[Date]>[2012/03/20]");
Date is a field in the record, and when I looked up records (with FTSearch), the date came back in the format above: [yyyy/mm/dd].
The parameter of the search is what I need here.
i.e. what should I put instead of "[Date]>[2012/03/20]"
I tried various constructions with Calendar and DateFormat, but it's not coming together...
Any suggestions?
You should get rid of the square brackets on the field name. The search method expects a Notes Formula, like what you'd put into a view selection formula:
"Date > [03/20/2012]"
It might also be required that dates are in mm/dd/yyyy format, though if you are in a non-US locale I'm not 100% sure.
You mentioned that you have been doing full text searches in the database, so it is definitely worth mentioning this... If the database actually has a full text index, then you may want to consider using the NotesDatabase.FTSearch() method instead of NotesDatabase.Search(). The FTSearch method will be considerably faster for a large database.
The syntax for FTSearch is different from the syntax for Search. You could use either "FIELD Date > 03/20/2012" or "[Date] > 03/20/2012".

How to send a Timestamp field to Oracle stored proc. from Java despite the DB config?

I'm making a request from a java webapp to an Oracle' stored procedure which happens to have a Timestamp IN parameter.
The way info travels is something like:
javaWebApp --} webservice client --} ws --} storedProcedure
And I send the Timestamp param as a formatted string from the webservice client to the ws.
In the testing environment, it works sending:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
input.setTimestampField(dateFormat.format(new Date()));
As you see, a formatted string is sent. But in the production environment, it raises an exception
ORA-01830: date format picture ends before converting entire input string.
It relates to the format not being the same, possibly due to differences in configuration from one DB to the other. I know the testing environment should be a replica of the production site, but it is not in my hands to set them properly. And I need to send the Timestamp-as-a-formatted-string field despite the way they setup the database. Any ideas? Thanks in advance.
**** EDIT ****: I've found the way to make it work properly despite the particular configuration. It is as simple as setting the call instruction in the web service with the appropiate Oracle instructions. I mean, the calling to the Oracle stored procedure went from
"call PACKAGE.MYPROCEDURE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
to
"call PACKAGE.MYPROCEDURE(?,?,?,?,?,?,TO_TIMESTAMP(?, 'DD-MM-YYYY HH24:MI:SS'),?,?,?,?,?,?,?,?,?,?,?)"
while the format I set in the procedure calling matches the format sent by the webapp using the SimpleDateFormat stated in the original question, slightly modified:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Thank you all for the help and the ideas.
The default NLS_DATE_FORMAT generally doesn't include the time and only a two-digit year. It is probably either DD-MM-YY or MM-DD-YY.
If the WS receives a string and the database stored procedure needs a timestamp, then the two of them will need to negotiate the format mask. Either the WS, when it connects to the database, should set an explicit date format, or the database should be able to accept a string and convert it using a hard-coded format.
Unless there is some particular negotiation you have defined in the WS, nothing the JavaWebApp or WebServiceClient will be able to influence the format that the database assumes the WS is using.
All that said, I'd have a look around any other code at your end and see if there's anything doing a similar translation. You may find something else using a specific format.
What does your query look like in the input prepared statement? That error indicates that Oracle doesn't like the date format you have passed in. Your test environment may have a different NLS_DATE_FORMAT set on the database or machine/driver being used.

Categories