开发者

Java : save data from UTF-8 file into Sql Server 2008

I failed to save da开发者_运维问答ta with accents from utf8 file into my SQL Server 2008 table - SQL collation = SQL_Latin1_General_CP1_CI_AS - (when I do a System.out.print of my insert statement : the accents are OK).

Here's the steps I'm doing :

1) Convert file to String :

        File f = new File(file);
        byte[] buffer = new byte[(int) f.length()];
        in = new DataInputStream(new FileInputStream(f));
        in.readFully(buffer);
        result = new String(buffer);

2) Execute insert :

            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            Properties properties = new Properties();
            properties.put("charSet", "ISO-8859-1");
            properties.put("user", user);
            properties.put("password", password);
            connection = DriverManager.getConnection("jdbc:jtds:sqlserver://" + serverName + ":1433;DatabaseName=" + dbName + "", properties);

            statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            statement.executeUpdate(sqlInsert, Statement.RETURN_GENERATED_KEYS);

Thanks for your help


To transcode UTF-8 character data to UTF-16 strings, provide the correct encoding to the String constructor.

new String(bytes, Charset.forName("UTF-8"));


Instead of setting charset to ISO-8859-1, set charset to UTF-8. ISO-8859-1 encoding does not accepts all the characters.

Thanks.


No matter which collation you use, it is important to use "N" before unicode data strings.

Like:

insert into table(somecolumn) values(N'unicode string')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜