Java + mysql Chinese garbled problem, javamysql Chinese garbled Problem

Source: Internet
Author: User

Java + mysql Chinese garbled problem, javamysql Chinese garbled Problem

There are multiple causes of garbled characters, one of which is because MySQL uses the ISO-8859-1 (Latin1) Character Set by default, while JAVA uses Unicode encoding internally, so when inserting data into the MYSQL database in JAVA, or when reading data, you must first convert the encoding method. Of course, if you can directly modify the configuration file, you can also solve the garbled problem. However, in some cases, we cannot directly access the configuration file (such as the space you bought online ), in this case, we can convert the encoding format.

 

Insert data:

For example:

...

String str = "Chinese ";

String SQL = "insert into Tb (xxx) values (?) "

PreparedStatement pstmt = conn. prepareStatement (SQL );

Pstmt. setString (1, str );

Pstmt.exe cuteUpdate ();

After this example is inserted into the mysqldata warehouse, you can view the data through mysql.exe connection. The inserted data becomes several "?" It is garbled.

Solution:

String str = "Chinese ";

Str = new String (str. getBytes (), "ISO8859_1"); // Add this sentence and encode it as a iso-8859-1

String SQL = "insert into Tb (xxx) values (?) "

PreparedStatement pstmt = conn. prepareStatement (SQL );

Pstmt. setString (1, str );

Pstmt.exe cuteUpdate ();

 

Read data:

The method is similar to inserting data, as shown below:

...

String str = rs. getString (1 );

Str = new String (str. getBytes ("ISO8859_1"); // restores from ISO8859-1 encoding to JAVA internal default Character Set

// Or str = new String (str. getBytes ("ISO8859_1"), "GBK ");

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.