Unable to insert Date into HSQLdb - java

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

Related

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.

SQL datetime from java

I'm trying to add a DATETIME value to the SQL database from Java. Actually I load the java.sql.Date object to an object array and then load the value into the prepared statement from the array.
This is my code:
java.util.Calendar cal = java.util.Calendar.getInstance();
java.sql.Date timestamp = new java.sql.Date(cal.getTimeInMillis());
values[0] = timestamp;
This is the exception that I am getting when I run the code:
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'UPDATE_DATE'.
Stack trace:com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'UPDATE_DATE'.
UPDATE_DATE is the column name in the table. Kindly help me out in this.
EDIT : This is the query:
INSERT INTO EXAMPLETABLE VALUES UPDATE_DATE=?,CONT_STATUS_NEW_ID=?,CONT_STATUS_DESC=?,LOCATION_ID=?,READ_STATUS=?,CONT_TYPE_ID=?,CONT_TYPE_DESC=?,CONT_ID=?
This is where the exception is thrown:
((PreparedStatementDataTarget) insertTarget).executeUpdate(values,arguments);
Actually you can't get anything out of the execute statement since it implements a lot of classes and custom methods. If there is anything wrong , then it should be in the logic which I use to add the date to the Object array (values) .
You are mixing insert and update syntax. You should either use
INSERT INTO tableName [(column list)] VALUES (values list)
Or
UPDATE tableName
SET column = value
[, column = value]
[WHERE condition]
Note #1: square brackets mean the part inside is optional.
Note #2: column list stands for column names delimited by a comma, values list stands for values delimited by a comma.

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.

SQL working on empty date

I am using java with jdbc to connecto to a MySQL database. I need to set one of date fields as empty. This field defaults to NULL and if i insert an empty string, the database creates a 0000-00-00 value in cell.
I then need to use that value in a report(jasperreport) and of course it can't be like 0000-00-00.
What I've tried to do:
Use if..then clause in query but i can't set it properly.
Has anyone an idea on how to get these date as empty string from the database (when I am calling jasperreport I am giving him just a sql query).
Set it to NULL in the DB, don't set it to an empty string.
Then write a select query which uses:
COALESCE(dt,'')
where dt is your date field.
Try this script as a test.
create table test(id int, dt datetime);
insert into test(id, dt) values (1, CURDATE());
insert into test(id, dt) values (2, NULL);
insert into test(id, dt) values (3, NOW());
insert into test(id, dt) values (4, NULL);
select
id, coalesce(dt, '') as dt
from
test;

Using oracle's to_date in preparedStatement

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

Categories

Resources