There is a system originally developed by delphi using the firebird database, building a database when the coding is not selected, of course, in delphi, the read and write Chinese are normal. The original system now need to add a feature to synchronize data from other databases, because it is a remote synchronization, data synchronization amount is not large, the frequency of four times a day intend to use an embedded jetty, write a simple handler achieve this function, The client uses httpclient for data upload. Https mode with two-way authentication between the client and the server.
Splinters meal scrawl, finally finished the base code, a run, dizzy, synchronization over the data, wrote the firebird, actually are garbled. Firebird jdbc driver jaybird by the manual says, jdbc connection string to add? Lc_ctype = GBK no use, still garbled.
After repeated tests to demonstrate the correct character to write to the database, another way I do not know, but the following methods of emergency, is good for something, the main idea is to use preparestatement, field content is written in a way parameter, all strings field, without setString method, instead of using setBytes manner, transcoding parameters with GBK.
The code snippet:
class.forName("org.firebirdsql.jdbc.FBDriver");
Connection conn = DriverManager.getConnection(
"jdbc:firebirdsql://localhost:3050/D:/db/card.fdb",
"sysdba", "masterkey");
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement("insert into CARDLOGCOPY values(?, ?, ?, ?, ?)");
try {
//循环插入新记录
for(int i = 0, n = records.size(); i < n; ++i) {
JSONArray record = records.getJSONArray(i);
for(int j = 0, m = record.size(); j < m; ++j) {
Object val = record.get(j);
if(val instanceof String)
pstmt.setBytes(j + 1, ((String)val).getBytes("GBK"));
else if(val instanceof Date)
pstmt.setString(j + 1, String.format("%tF %<tT", val));
else
pstmt.setObject(j + 1, val);
}
pstmt.execute();
pstmt.clearParameters();
}
conn.commit();
}
catch (Exception e) {
rollback(conn); //回滚事务
logger.error("数据库操作出错,事务回滚.", e);
throw e;
}
finally {
pstmt.close;
conn.close;
}
Reproduced in: https: //my.oschina.net/kivensoft/blog/549365