• 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. }

  • 相关阅读:
    黄金投资新手指南:投资现货黄金怎样开户?
    2023最新版ESP8266 Arduino Http网页结果存入LittleFS文件
    数据库开发-MySQL
    使用 OpenCV 的文档扫描仪
    生产者消费者模式进阶-设计模式-并发编程(Java)
    MySQL的基础(一)
    【前段基础入门之】=>CSS浮动
    自己动手写一个分库分表中间件(九)兼容性处理之事务之 Spring 怎么看是一个事务
    通过玩游戏学会AWS
    ARP安全综合功能示例
  • 原文地址:https://blog.csdn.net/m0_59252007/article/details/125477784