SQL datetime from java - 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.

Related

Java prepairedStatement setInt is adding quotes in the SQL

I have a simple SQL statement that I want to execute via
String tokenInsQ = "INSERT INTO pitweb.tokens (token_user_id,token_token,token_valid,token_refresh) (?,?,?,?)";
try {
PreparedStatement p = SQL.dbConnection.prepareStatement(tokenInsQ);
p.setInt(1, r.getInt("user_id").intValue());
p.setString(2, token.getString("token"));
p.setTimestamp(3, (Timestamp)token.get("valid"));
p.setTimestamp(4, (Timestamp)token.get("renew"));
System.out.println(p);
p.executeUpdate();
p.close();
}
I expect this to work just fine. Token is a long string and r.getInt("user_id").intValue() Returns 11. The error I keep getting is
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
Position: 82
So I added the print statement to see the SQL that it is trying to execute. The program Prints.
INSERT INTO pitweb.tokens (token_user_id,token_token,token_valid,token_refresh) ('11','really long string ','2020-03-17 13:15:22.847000 -05:00','2020-03-14 13:15:22.847000 -05:00')
I assume that my problem is that the token_user_id ('11') is in quotes. Is this because of the way that I created the Prepared Statement? or do I have a different problem. the output seems vague to me
Here is what the token table looks like
CREATE TABLE pittweb.token
(
token_id integer NOT NULL DEFAULT nextval('pittweb.token_token_id_seq'::regclass),
toekn_user_id integer,
token_valid timestamp without time zone,
toekn_refresh timestamp without time zone,
token_token text COLLATE pg_catalog."default",
CONSTRAINT token_pkey PRIMARY KEY (token_id),
CONSTRAINT token_toekn_user_id_fkey FOREIGN KEY (toekn_user_id)
REFERENCES pittweb."user" (user_id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
WITH (
OIDS = FALSE
)
There is a typo in toekn_refresh as well along with toekn_user_id.
There is a typo in the column name toekn_user_id. In the insert statement, you have used token_user_id and in the DDL it is toekn_user_id

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

Invalid character value for cast specification on column number

I have an access database with address attribute as "Text" data type. In my java/jdbc code, I'm using resultset to retrieve the address value using select query.
Generally, for sql database, It works with String address= resultset.getString();
but, since it's access db how do I query it?
As, I'm using the String address= resultset.getString(); statement, I'm getting following exception:
Invalid character value for cast specification on column number
Specify the column name or the index of the column while getting the resultset values.
like,
String value= resultset.getString(1); // if the text is in the first column

How can I insert null data?

I want to insert null data to Teradata with JDBC connection on JAVA.
First of all I try this:
PreparedStatement stmt;
String qm="Insert into db.user values (?,?,?,?,?,?,?)";
connection= DriverManager.getConnection
(
"jdbc:teradata://192.xxx.x.xx/database=DBC,tmode=ANSI,charset=UTF8","user","passw0rd" );
stmt = connection.prepareStatement(qm);
//some code here to open while loop
stmt.setObject(i,null); // This isnt working with Terada JDBC. It is working for Oracle and MSSQL JDBC
//and I finish my code
And after, that I tried this instead of stmt.setObject(i,null); :
stmt.setNull(i,rsmd.getColumnType(i),rsmd.getColumnTypeName(i));
rsmd.getColumnType(i) is equal to 97
rsmd.getColumnTypeName(i) is equal to DATE
Yes it is true my field is DATE.
But it gives this ERROR:
ERROR : [Teradata JDBC Driver] [TeraJDBC 14.10.00.17] [Error 857] [SQLState HY000] Two different data types are being set for parameter 17 (449 & 749)
How can I fix this.
I used in the past the setNull(i, Types.#field type#) in a custom DB layer for TD.
However if you search the codes returned in the exception you'll find that they represent a Date and a Varchar, as if, at the same position, you sometimes pass a Date type and sometimes a Varchar.
Are you by chance passing not null dates as Date-like strings (e.g. "2015-08-18"), and not as java.sql.Date objects?
If that's the case you should change the code to use java.sql.Date objects and this will solve your issue.
Typically if you wish to INSERT a NULL value into ColC I would suggest using the following method with your INSERT ... VALUES statement:
INSERT (ColA, ColB, ColD, ColE) VALUES (1000, 'Testing Null', 1.00, DATE '2013-06-30);
Teradata will take the absence of the column in the INSERT statement to place either the pre-defined DEFAULT value or NULL for the column.
What if you try the following:
stmt.SetNull(i,Types.NULL)
The workaround for this issue is to cast the NULL to be a VARCHAR, so that it is compatible.
INSERT INTO XYA(PKEY,REF_KEY) VALUES(2,cast(null as varchar(10)));

Resultset.getDate() throwing exception java.lang.NumberFormatException: For input string: "Name of Month"

When extracting date from database using Resultset.getDate(), I am getting the following exception:
java.lang.NumberFormatException: For input string: "Name of Month".
I can confirm that the exception is thrown when trying to get data from a column of Oracle date datatype.
I can't paste the actual code here as it is very long. But the sample code is as given below
pstmnt = connection.prepareStatement(selectQuery);
rs = pstmnt.executeQuery();
while (rs.next()) {
rs.getDate(column.getColName());
}
Please help?
As requested by Sanjay, please find the stack trace below
java.lang.NumberFormatException: For input string: "MAY"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:63)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:531)
at java.sql.Date.valueOf(Date.java:200)
at oracle.jdbc.driver.OracleStatement.getDateValue(OracleStatement.java:4610)
at oracle.jdbc.driver.OracleResultSetImpl.getDate(OracleResultSetImpl.java:625)
at oracle.jdbc.driver.OracleResultSet.getDate(OracleResultSet.java:1601)
at quotecopy.DbConnection.getTableRows(DbConnection.java:126)
at quotecopy.QuoteCopier.main(QuoteCopier.java:66)
java.lang.NumberFormatException: For input string: "MAY"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:63)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:531)
at java.sql.Date.valueOf(Date.java:200)
at oracle.jdbc.driver.OracleStatement.getDateValue(OracleStatement.java:4610)
at oracle.jdbc.driver.OracleResultSetImpl.getDate(OracleResultSetImpl.java:625)
at oracle.jdbc.driver.OracleResultSet.getDate(OracleResultSet.java:1601)
at quotecopy.DbConnection.getTableRows(DbConnection.java:127)
at quotecopy.QuoteCopier.main(QuoteCopier.java:66)
Can you check your query, i believe you are using to_char on the Date column which is causing the getDate unable to recognize it as a valid Date
please refer http://forum.springsource.org/showthread.php?19783-Oracle-JDBC-Date-Problem.
May be it would help you
rs.getString() or rs.getDate() retrieves based on your database table column name. Can you verify that the column containing the date is named "Name of Month" ?
A few things you might want to check out:
Is the column type of this column in database really date/datetime?
What happens when you print out getObject() instead of getDate()? Can you show us the output?
What happens when you use column indices to retrieve the date instead of using column name?
Based on the information provided, it would be worth checking for the following scenarios in the codebase:
Reading a column that is not of type DATE in the Oracle database. The Oracle JDBC driver maps the Oracle database type DATE to the java.sql.Date type; actually it is the oracle.sql.Date type, which is a subtype of the java.sql.Date type. If you are not reading a column of type Oracle DATE, but instead a TIMESTAMP field, then you might encounter the exception. You would therefore have to use a suitable method - likely to be getTimeStamp, to read the data in the column.
The NLS_DATE_FORMAT used in the database is different from the date format expected by the JDBC driver. This would either require you to change the NLS_DATE_FORMAT on creating a session, using a logon trigger, or it would require you to use TO_CHAR function calls with appropriate date formats in your SQL queries.
Accessing the columns in the ResultSet in a random manner. Most JDBC drivers will expect you to read the contents of the result set, column by column starting at the first column, without allowing you to ignore any columns. If you attempted reading a column while ignoring the previous ones, then you might encounter this exception.

Categories

Resources