java項目向mysql中寫入emoji表情

來源:互聯網
上載者:User

標籤:cti   builder   ase   lob   utf8   l資料庫   mysql資料庫   mys   dep   

前提:mysql資料庫版本不能低於5.5。

第一種方法:百度一搜一大堆,主要內容就是:修改mysql設定檔(需要重啟資料庫),修改表和欄位的編碼,都改成utf8mb4。

 

第二種方法:從jdbc入手,每次調用資料庫前執行一下 set names utf8mb4;

使用druid資料來源的項目,可以在設定檔中增加<property name="connectionInitSqls" value="set names utf8mb4;"/>,

其他資料來源應該也有類似的配置。

 

第三種方法:將要存入的內容重新編碼,寫入前用new BASE64Encoder().encode()編碼,從資料庫讀取後用new BASE64Decoder().decodeBuffer()解碼。

 

第四種方法:使用blob類型儲存emoji表情,blob類型是二進位類型,不關心編碼格式,讀取之後轉成String即可。

 

另類方法:這個不算是解決寫入emoji方法,只是在代碼中把emoji內容過濾掉(有點暴力),防止寫入資料庫報錯。

public static String filterUtf8mb4(String str) {final int LAST_BMP = 0xFFFF;StringBuilder sb = new StringBuilder(str.length());for (int i = 0; i < str.length(); i++) {int codePoint = str.codePointAt(i);if (codePoint < LAST_BMP) {sb.appendCodePoint(codePoint);} else {i++;}}return sb.toString();}

  emoji字元對應的code point 大於 U+FFFF,把這些過濾掉再寫入資料庫就不會報錯了。 code point參考:http://www.cnblogs.com/chrischennx/p/6623610.html

java項目向mysql中寫入emoji表情

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.