• Mysql入库不了表情符号怎么办


    目录

    前言

    异常信息:

    主要原因是

     解决办法


    前言

    异常信息:

    ### The error occurred while setting parameters ### SQL: INSERT INTO news_info ( id,  title, content, author, summary, sensitives, scraping_time, level, news_type, content_text, original_columns, content_words ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )

    ### Cause: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\x89' for column 'author' at row 1 ;

    uncategorized SQLException; SQL state [HY000];

    error code [1366];

    Incorrect string value: '\xF0\x9F\x91\x89' for column 'author' at row 1;

    nested exception is java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\x89' for column 'author' at row 1 at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:89)

    主要原因是

    author  含有表情符号,表情是4字符,如果Mysql建库建表的时候没有声明是4字节,那么是在insert的时候会报错的!

     解决办法

    需要在消费入库的时候进行author转换成正常的二进制,二字符的汉字,也就是剔除四字节的表情;

    String  author=  ContentUtils.filterOffUtf8Mb(newsInfo.getAuthor());
    newsInfo.setAuthor(author);

    主要得工具类代码

    1. /**
    2. * 主要功能是做表情包剔除工具类
    3. * @param text
    4. * @return
    5. */
    6. public static String filterOffUtf8Mb(String text) {
    7. if (StringUtils.isBlank(text)) {
    8. return text;
    9. }
    10. String result = text;
    11. try {
    12. byte[] bytes = text.getBytes(UTF_CHARACTOR);
    13. ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    14. int i = 0;
    15. while (i < bytes.length) {
    16. short b = bytes[i];
    17. if (b > 0) {
    18. buffer.put(bytes[i++]);
    19. continue;
    20. }
    21. // 去掉符号位
    22. b += 256;
    23. if (((b >> 5) ^ 0x06) == 0) {
    24. buffer.put(bytes, i, 2);
    25. i += 2;
    26. } else if (((b >> 4) ^ 0x0E) == 0) {
    27. buffer.put(bytes, i, 3);
    28. i += 3;
    29. } else if (((b >> 3) ^ 0x1E) == 0) {
    30. i += 4;
    31. } else if (((b >> 2) ^ 0xBE) == 0) {
    32. i += 5;
    33. } else {
    34. i += 6;
    35. }
    36. }
    37. buffer.flip();
    38. result = new String(buffer.array(), UTF_CHARACTOR);
    39. } catch (Exception ex) {
    40. log.error("内容过滤4字节字符出现错误" + ex.getMessage());
    41. }
    42. return result;
    43. }

  • 相关阅读:
    Go 语言 select 都能做什么?
    VC编译器编译命令cl、rc、link
    【SpringBean】bean的作用域和bean的生命周期
    千万级订单生成的痛点与架构
    Leetcode(665)——非递减数列
    【SpringBoot实践】事务和事务传播机制&失效原因&正确使用事务的建议
    Java面试
    Telink泰凌微TLSR8258蓝牙开发笔记(二)
    Jupyter Notebook的使用
    10、Java——吃货联盟订餐系统(基础知识)
  • 原文地址:https://blog.csdn.net/m0_59252007/article/details/125477784