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