SQL Server Nvarchar and Java prepared statement

2019-06-27 18:35发布

问题:

I have a question regarding inserting strings to SQL Server 2008 R2. When I try to insert strings with some national letters, I receive "?" instead.

I know that adding N at the beginning of a string literal will fix this problem, but I'm using JDBC prepared statements, like this:

INSERT INTO MyTable(col1, col2) VALUES (?,?);

My question is: How I can add this "N" letter? Should I do something like this?

INSERT INTO MyTable(col1, col2) VALUES (N?,N?);

To be honest I'm not convinced because this is not working at all.

回答1:

Based on comments written by @a_horse_with_no_name and @gofr1 there are 2 solutions:

  1. Change sendStringParametersAsUnicode - this cause that all string will be treated as "N" Strings (this is globally change)

  2. Use PreparedStatement.setNString() instead of setString() - and this is "local" change.

Both are working - use which fits better to your needs :)