Using oracle's to_date in preparedStatement - java

I am trying to enter a date in oracle database using to_date in preparedStatement but I am getting errors.
Code Fragments:
sql = "select Identifier from metadata where content_cdate >=to_date(?,'dd-mm-yyyy') and content_cdate < to_date(?,'dd-mm-yyyy') and status='published' and content_mdate is null";
ps.setString(1, commonUtil.dateToString(startTime));
the dateToString method returns a value like this: 2012-01-01 12:00:00
Error:
[Oracle][ODBC][Ora]ORA-01861: literal does not match format string
Please advice.

You should use a correct TO_DATE format mask to match your input.
In your case most likely: TO_DATE(?,'YYYY-MM-DD HH24:MI:SS')

Related

Converting input date string to SQL date type

I have looked all over for this answer for a whole day but I'm not getting anywhere.
I have a string that is formatted like this:
dd/mm/yyyy
I want to enter this in to a SQL database
The database field (of type Date) shows the format as yyyy-mm-dd.
At the moment I have the following code:
String inputDate = dateBookingEntry.getText();
LocalDate interDate = LocalDate.now();
interDate.parse(inputDate,DateTimeFormatter.ofPattern("dd/MM/yyyy"));
java.sql.Date finalDate = java.sql.Date.valueOf(interDate);
When I enter the date 12/12/2020 as the string, I get the error message:
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near ''2020-01-29'
I don't get what I'm doing wrong, or how to fix it. I get that it's showing the current date and not the entered date, but even if that was the problem, why would it show an SQL Syntax error?
What should I change here for it to work?
EDIT:
The SQL insertion code to this table looks like this:
st.executeUpdate("INSERT INTO `fitnessClasses`(`session`, `date`, `price`, `trainer`, `level`, `type`) VALUES ('"+session+"', '"+sqlDate+"', '"+price+"', '"+trainer+"', '"+level+"', '"+classType+"')");
The full SQL code mentioned above with the error looks like this:
ResultSet result = st.executeQuery("SELECT * FROM `fitnessClasses` WHERE `session` = '"+session+"' AND `date` '"+finalDate+"' AND `type` = '"+classType+"' AND `level` = '"+level+"'");
EDIT 2:
OK, I now realise I was missing an =.
Now the SQL SELECT works but it searches for today's date and not the entered date
I think you want the class-level of parse such as
LocalDate interDate = LocalDate.parse(inputDate blah blah)
Currently you are setting interDate to now() which is the current date and that is why you end-up with today's date and not the date entered.

Unable to insert Date into HSQLdb

I am using HSQL as an in memory database for testing. However, I am unable to insert a date into the column.
Below is my table creation script:
SET DATABASE SQL SYNTAX ORA TRUE;
create table OWN_TABLE (
ID DECIMAL NOT NULL,
NAME VARCHAR(24) NOT NULL,
CAPACITY_SUPPLY_DATE DATE ,
);
And the queries I tried:
INSERT INTO OWN_TABLE(ID, NAME, CAPACITY_SUPPLY_DATE) VALUES(2, '4813', '2090-07-15');
But it gives
Caused by: java.sql.SQLDataException: data exception: invalid datetime format
I also tried 2090-07-15 00:00:00 but it didn't work.
Assuming oracle syntax might work, I tried:
INSERT INTO LABS_CAPACITY_SUPPLY(ID, SHIP_NODE, CAPACITY_SUPPLY_DATE) VALUES(1, '4813', 'TO_DATE(2090-07-30,"yyy-MM-dd")');
But got Unparseable date: "TO_DATE(2090-07-30,"yyy-MM-dd")"
Can somebody please tell me the right way to insert dates into HSQL. I have the 2.3.2 jar.
Use a proper standard SQL date literal:
INSERT INTO OWN_TABLE
(ID, NAME, CAPACITY_SUPPLY_DATE)
VALUES
(2, '4813', DATE '2090-07-15');
Or, if you do want to use the to_date() function then don't put it into single quotes.
INSERT INTO LABS_CAPACITY_SUPPLY
(ID, SHIP_NODE, CAPACITY_SUPPLY_DATE)
VALUES
(1, '4813', TO_DATE(2090-07-30,'yyy-MM-dd'));
Note that for the to_date() function the case of the format string does not matter. 'yyyy-MM-dd' is the same as 'YYYY-MM-DD' or 'yyyy-mm-dd'. The format is not the one used for Java's SimpleDateFormat.
If you are doing this from within a Java program you should not use any of the above solutions. Use a PreparedStatement instead:
java.sql.Date dt = ...;
PreparedStatement pstmt = connect.prepareStatement("INSERT INTO OWN_TABLE(ID, NAME, CAPACITY_SUPPLY_DATE) VALUES(?,?,?)";
pstmt.setInt(1, 2);
pstmt.setString(2, "4813");
pstmt.setDate(3, dt);
How you construct the instance of java.sql.Date depends on where you get the data from. You could use a SimpleDateFormat to parse the user's input. Or you could use LocalDate if you are using Java 8, e.g. java.sql.Date.valueOf(LocaleDate.of(2090,7,30))

JDBC4 insert date "0001-01-01"

I want to insert "0001-01-01" as a value into a date field by using Java PreparedStatement.
But it throws exception when I tried this:
String sql = "insert into mytable values(?)"
ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("0001-01-01"));
ps.executeUpdate(); // throws exceptions here.
The error is :
The supplied value is not a valid instance of data type datetime. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
If I don't use PreparedStatement, I can insert "0001-01-01". However,
prepare statement seems not allow me to insert this value.
It will work if I inserted "1969-01-01" instead of "0001-01-01".
Any ideas?
Updates:
Here are more info that might be needed.
we use sql server 2012.
we have to use "0001-01-01" because these values were already there. I am changing some very very old codes to use prepare statement. So I have to insert the same values in the same functionality.
Updates 2:
We are using "date" datatype, not "datetime" datatype.
Based on this https://msdn.microsoft.com/en-us/library/bb630352.aspx, "0001-01-01" is not out of range for "date" field.
In addition, I am able to insert "0001-01-01" to the date field without using prepare statement. i.e.
String sql = "insert into mytable values('0001-01-01')"
java.sql.Statement statement = conn.createStatement();
statement.executeUpdate(sql);
So it is not sql server's problem or db field's problem.
Try using the different suitable JDBC driver.

PreparedStatement

I am using PreparedStatement's setString method to set values for the start and end dates in a sql query.
String sql = "..... " AND tableA.time BETWEEN ? " +
" AND ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, startDate);
st.setString(2, endDate);
The values however are not being set. I understand that normally there is an equals sign:
"tableA.member_id = ?" +"
How do I than call setString method when I am using a 'Between' operator in the sql statement? Hope someone can advise. Thank you.
See http://docs.oracle.com/cd/B28359_01/server.111/b28286/conditions011.htm
"BETWEEN" can be used with datetime data types. However, if tableA.time is a datetime field of some kind (Timestamp, etc.), using st.setString(...) won't work. You need to use setDate(dt) or setTimestamp(ts) instead. See Using setDate in PreparedStatement for more info.
Use setDate.
Is your startDate and endDate a java.util.Date object?
If it is, you can use this code.
st.setDate(1, new java.sql.Date(startDate.getTime()));
st.setDate(2, new java.sql.Date(endDate.getTime()));
If it is not. Convert that first ro java.util.Date object.
BETWEEN expects its arguments to have a type that is compatible with the column being tested. Giving it string arguments for a date column won't work.
You could add a function to the SQL in order to convert the string to a date (I don't know what database you're using, this example uses Oracle's to_date function):
from tableA.time BETWEEN to_date(?, 'yyyy/mm/dd') AND to_date(?, 'yyyy/mm/dd')
Alternatively you could leave the SQL alone and use setDate on the PreparedStatement, like:
setDate(1, new SimpleDateFormat("yyyy/MM/dd").parse(startDate));
This second way is more usual, it has the advantage of avoiding having to add a date-conversion function (that may be non-standard) to your SQL.
But you would have to do the conversion on one side or the other. The database's SQL parser won't convert it for you. If the database took responsibility for the conversion and there was a mistake it could introduce data errors silently, the less error-prone alternative is for the application developer to tell the database how the date string should be converted.

Converting a Date from a String representation to a numerical representation and back again

Are there any patterns or known ways of converting a date from a string representation to a numerical representation and vice versa?
Background:
I am using an Apache Derby database as the persistence for a Java program. I would like to do something like this:
Select * from MyTable where date_column > 20100914154503 order by date_column DESC
// 20100914154503 = 2010-09-14 15:45:03
My dates are stored in my java program I am using Joda Time ( https://www.joda.org/joda-time/) DateTime object.
Thanks
I'm not too sure what you're actually trying to do or why you need to use a string at all, but in general you should use a PreparedStatement. Then you can just set the date in the PreparedStatement using a java.sql.Timestamp:
DateTime date = ...;
Connection conn = ...;
PreparedStatement ps = conn.prepareStatement(
"Select * from MyTable where date_column > ? order by date_column DESC");
ps.setTimestamp(1, new Timestamp(date.getMillis()));
Strongly consider looking into how your database manages dates and time, since it can probably do what you need. Remember that the date you have should be stored in a date field in the database table.

Categories

Resources