Java+mysql Chinese garbled problem

Source: Internet
Author: User

There are several reasons for garbled problems, one of which is because MySQL uses the iso-8859-1 (or Latin1) character set by default, while Java internally uses Unicode encoding, so when inserting data into the MySQL database in Java, or when reading data, You need to change the encoding first. Of course, if you can directly modify the configuration file, you can also solve the garbled problem, however, in some cases, we do not have direct access to the configuration file (for example, you are buying online space), at this time, we can take the encoding format conversion method.

Insert data:

Such as:

...

String str= "Chinese";

String sql = "INSERT into Tb (XXX) VALUES (?)"

PreparedStatement pstmt = conn.preparestatement (sql);

Pstmt.setstring (1,STR);

Pstmt.executeupdate ();

When this is inserted into the MySQL database, the data can be viewed with the Mysql.exe connection, and the inserted data becomes a few "? "To be, also become garbled."

The workaround is to:

String str= "Chinese";

str = new String (Str.getbytes (), "iso8859_1"); Add this sentence and change the code to ISO-8859-1

String sql = "INSERT into Tb (XXX) VALUES (?)"

PreparedStatement pstmt = conn.preparestatement (sql);

Pstmt.setstring (1,STR);

Pstmt.executeupdate ();

Read data:

The method is similar to inserting data, as follows:

...

String str = rs.getstring (1);

str = new String (str.getbytes ("iso8859_1")); Revert to the Java internal default character set by Iso8859-1 encoding

or str = new String (str.getbytes ("Iso8859_1"), "GBK");

Java+mysql Chinese garbled problem

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.