出于某种奇怪的原因,我似乎无法UTF-8的数据添加到我的MySQL数据库。当我输入一个非拉丁字符时,它被存储为?????。其他一切都存储正常。例如,“这是一个example®™”存储的很好,但“和英辞典”存储为“????”。不能存储在MySQL UTF-8的内容使用Java的PreparedStatement
连接URL是好的:
private DataSource getDB() throws PropertyVetoException {
ComboPooledDataSource db = new ComboPooledDataSource();
db.setDriverClass("com.mysql.jdbc.Driver");
db.setJdbcUrl("jdbc:mysql://domain.com:3306/db?useUnicode=true&characterEncoding=UTF-8");
db.setUser("...");
db.setPassword("...");
return db;
}
我使用PreparedStatement的你所期望的,我甚至尝试进入“设置名称UTF8”有人建议。
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = db.getConnection();
stmt = conn.prepareStatement("set names utf8");
stmt.execute();
stmt = conn.prepareStatement("set character set utf8");
stmt.execute();
... set title...
stmt = conn.prepareStatement("INSERT INTO Table (title) VALUES (?)");
stmt.setString(1,title);
stmt.execute();
} catch (final SQLException e) {
...
表本身似乎要被罚款。
Default Character Set: utf8
Default Collation: utf8_general_ci
...
Field title:
Type text
Character Set: utf8
Collation: utf8_unicode_ci
我通过输入以Unicode测试了它(“和英辞典”特异性)通过GUI编辑器,并从表中选择 - 和它返回就好了。所以这似乎是JDBC的一个问题。
我错过了什么?
你确定'title'有正确的内容吗?也许你从一个使用ISO的文件读取它 - 无论什么? – 2012-03-08 22:11:26
是的,当我在标题上放置一个断点时,我可以看到它确实是unicode(例如:和英辞典),而不是? – nostromo 2012-03-08 22:33:44
'utf8'是一个字符串,所以用引号括起来:''set names'utf8'“'。不要混淆字符集。 – 2012-03-08 22:55:14