出於某種奇怪的原因,我似乎無法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