Java Project writes emoji expression to MySQL

Source: Internet
Author: User

Premise: MySQL database version can not be less than 5.5.

The first method: Baidu a search a lot of, the main content is: Modify the MySQL configuration file (need to restart the database), modify the table and field encoding, are changed to UTF8MB4.

The second method: Starting with JDBC, execute the Set names UTF8MB4 before each call to the database;

Using the Druid Data source project, you can add <property name= "Connectioninitsqls" value= "set names UTF8MB4 in the configuration file." />,

Other data sources should also have similar configurations.

The third method: re-encode the content to be deposited, using the new Base64encoder (). Encode () encoding before writing, and decoding from the database with the new Base64decoder (). Decodebuffer ().

Fourth method: Use BLOB type to store emoji expression, blob type is binary type, do not care about encoding format, read and then turn to string.

Alternative method: This is not a solution to write emoji method, just in the code to filter out the emoji content (a bit of violence), to prevent writing database error.

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.codepoin TAt (i); if (Codepoint < last_bmp) {sb.appendcodepoint (codepoint);} else {i++;}} return sb.tostring ();}

The emoji character corresponding to the code point is greater than u+ffff, filtering out and then writing to the database will not be an error. Code Point Reference: Http://www.cnblogs.com/chrischennx/p/6623610.html

Java Project writes emoji expression to MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.