How can I insert null data? - java

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

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.setString on int/numeric columns in PostgreSQL JDBC

I am working with some legacy code that performs database operations in a generic way, so that the User/developer can work with a different database by changing only the JDBC driver.
I have a problem with PostgreSQL JDBC driver. My test case:
//ddl
CREATE TABLE test
(
id numeric,
name text,
)
//java code
String sqlCmd = "INSERT INTO test values (?, ?)";
PreparedStatement ps = connection.prepareStatement( sqlCmd );
ps.setString( 1, "1" );
ps.setString( 1, "name1" );
ps.executeUpdate();
With Postgres, the result of this case is an exception with message: "can't cast string to int..."
Is it inappropriate to use PreparedStatement.setString() to set values that database expects to be numeric?
Should I expect the JDBC driver to automatically convert java types to database types?
This test passes with other databases, including H2 and MySQL. Does the failure with PostgreSQL reflect a bug in the JDBC driver? Is it possible to make this case work without changing code?
The documentation for java.sql.PreparedStatement has this to say:
Note: The setter methods (setShort, setString, and so on) for setting IN parameter values must specify types that are compatible with the defined SQL type of the input parameter. For instance, if the IN parameter has SQL type INTEGER, then the method setInt should be used.
Whether a particular database or JDBC driver allows you to be sloppy about that is its own affair, but you are not justified in expecting that all drivers will allow such slop, even if certain ones do.
while migrating from oracle database to postgresql, I found that may help you to use setString with numeric types and date types as well.
Just you have to use the connection parameter stringtype=specified as mentioned in the documentation.
https://jdbc.postgresql.org/documentation/head/connect.html
You are using setString() method to insert integers and postgres could not do that, Use
ps.setInt(1, INTEGER_VALUE);

Error when inserting through JDBC

When I run the sql statement below through psql it works fine, but when I try to run the same query by building it with a preparedstatement, it fails.
INSERT INTO Hvbp
(provider_number, weighted_clinical_process,
weighted_patience_experience, total_performance_score,
coordinates, latitude, longitude, address, city, state, zip)
VALUES
('010092', 43.909090909091, 13.5, 57.409090909091,
'POINT(33.206201 -87.525480)', 33.206200613000476,
-87.52548020899968, '809 UNIVERSITY BOULEVARD EAST', 'TUSCALOOSA', 'AL', '');
The error I keep getting is
org.postgresql.util.PSQLException: ERROR: column "coordinates" is of type geography but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
Position: 203
The coordinates column is of type GEOGRAPHY(POINT)
I know this is an old problem, but I just spend most of the day debugging the same basic problem and finally found a fix
What you're trying to do, is provide the POINT using WKT and have the server automatically convert that into a Geometry.
And as you've found that works if you include the WKT inside the body of the SQL, but fails if you use a parameter on a prepared statement.
There are 3 options for fixing it:
Use st_GeographyFromText in your SQL like so:
INSERT INTO Hvbp(coordinates) VALUES( st_GeographyFromText(?) )
And then set your parameters as WKT with setString.
Depending on the frameworks involved, that might not be possible for you.
Use setObject on the preparedStatement instead of setString. For example:
ps.setObject(1, "POINT(33.206201 -87.525480)", java.sql.Types.OTHER )
Change your JDBC driver settings to send strings as unspecified type, and then the server will do type conversions for you. To do that you want to change your JDBC URL to something like
"jdbc:postgresql:my_db?stringtype=unspecified"
#Tim - thank you for your help with a similar problem - I had to write ST_GeometryFromText into my database and the JDBC Driver threw a similar exception as #Hanks got.
For further reference and clarification for others - this is my result using Java with JDBC:
INSERT INTO streets.points ( point_id, the_geom )
VALUES( ?, ST_GeomFromText( ? , 25832) );
And the inserted Geometry-String looked like that:
POINT(33.206201 -87.525480)

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