JDBC: Cannot coerce host var to type nchar
When using JDBC to persist a row in which each column is set to a string value containing only uppercase latin letters (e.g. char_col=KFX, varchar_col=J, nchar_col=XZDFOY, nchar_varying_col=YYCY), I get the following exception:
Caused by: cubrid.jdbc.driver.CUBRIDException: Semantic: Cannot coerce host var to type nchar.
at cubrid.jdbc.driver.CUBRIDConnection.createCUBRIDException(CUBRIDConnection.java:829)
at cubrid.jdbc.driver.CUBRIDStatement.checkExecuteError(CUBRIDStatement.java:941)
at cubrid.jdbc.driver.CUBRIDStatement.executeCoreInternal(CUBRIDStatement.java:830)
at cubrid.jdbc.driver.CUBRIDStatement.executeCore(CUBRIDStatement.java:791)
at cubrid.jdbc.driver.CUBRIDPreparedStatement.executeUpdate(CUBRIDPreparedStatement.java:140)
at org.databene.platform.db.DBSystem.persistOrUpdate(DBSystem.java:867)
... 44 more
The code that provoked the error was something like this:
PreparedStatement statement = ...;
statement.setObject(1, "KFX");
statement.setObject(2, "J");
statement.setObject(3, "XZDFOY");
statement.setObject(4, "YYCY");
int rowCount = statement.executeUpdate();
The table definition is
create table chartest (
char_col char(4) not null,
varchar_col varchar(8) not null,
nchar_col nchar(6) not null,
nchar_varying_col nchar varying(10) not null
);
What's wrong?
Regards, Volker
Dear Volker,
NCHAR and NVARCHAR data types were originally developed to provide a support for non-English characters, otherwise called national characters. In the upcoming new CUBRID release we will introduce full support for Unicode characters through national character sets. Therefore,
- NCHAR and NVARCHAR will be deprecated, so we do not recommend using it in a project. If necessary, just use CHAR and VARCHAR types.
- If you try to use it in JDBC like
statement.setObject(3, "XZDFOY");
... you will receive a server error saying "Cannot coerce host var to type nchar". Or if you directly specify the target SQL type likestatement.setObject(3, "XZDFOY", java.sql.Types.NCHAR);
... you will receive a JDBC Exception saying "SQL feature is not supported".
So do not use these data types. The SQL syntax to insert NHCAR type, though, is:
INSERT INTO tbl VALUES (N'some NChar or NVarChar');
Thank you for answering. Unfortunately the answer does not help, so let me put this in other terms:
I understand and agree that people should not use the nchar types in future applications, but yet they exist and are supported by the database, so they must be supported in the JDBC driver in the way I described. I consider the observerd behaviour to be a bug.
I am working on a tool to generate data for databases and need to support any type of the respective target system, so can you give me advice how to write nchar data using PreparedStatement.setObject()? It is supposed to accept a string for an nchar column and convert it to the appropriate internal type automatically. At least this is what all other open source databases do.