記錄解決emoji表情存入myql資料庫報錯
阿新 • • 發佈:2018-11-07
utf-8編碼可能2個位元組、3個位元組、4個位元組的字元,但是MySQL的utf8編碼只支援3位元組的資料,而移動端的表情資料是4個位元組的字元。如果直接往採用utf-8編碼的資料庫中插入表情資料,Java程式中將報SQL異常:
java.sql.SQLException: Incorrect string value: ‘\xF0\x9F\x92\x94’ for column ‘name’ at row 1
解決1:修改資料庫,表,欄位的編碼為utf8mb4
修改my.ini檔案
1. 修改my.cnf 或 my.ini [mysqld] character-set-server=utf8mb4 [mysql] default-character-set=utf8mb4 修改後重啟Mysql
由於修改配置檔案可能影響較多專案,所以沒用此方法。
解決2:採用base64加解密
3、引入jar包:
加入jar包依賴(如果是maven專案就直接在pom檔案中加入下邊內容,若不是就加入對應jar包)
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
import/** * 將String型別的字串進行base64編碼與解碼,使用utf-8 */ public class Base64Util {
private static final Logger logger = LoggerFactory.getLogger(Base64Util.class);
/** * 對給定的字串進行base64加密 */ public static String encodeData(String inputData) { try { if ( null == inputData) { return null; } return new String(Base64.encodeBase64(inputData.getBytes( "utf-8")), "utf-8"); } catch (UnsupportedEncodingException e) { logger.error(inputData, e); }
return null; } /** * 對給定的字串進行base64解密 */ public static String decodeData(String inputData) { try { if ( null == inputData) { return null; } return new String(Base64.decodeBase64(inputData.getBytes( "utf-8")), "utf-8"); } catch (UnsupportedEncodingException e) { logger.error(inputData, e); }
return null; }
}