Java database connection Encoding

Source: Internet
Author: User

Reprinted: http://hi.baidu.com/sosyq_bd/blog/item/c42d8330b8db7557ad4b5f94.html

In Java, the string encoding format is Unicode. If you want to insert Chinese characters into MySQL, the encoding attribute of the character column in the table should be set to UTF-8.

Create Table seugs (

Number int (11) default null,

Name nchar (10) default null,

Sex nchar (4) default null,

Home nchar (100) default null,

College nchar (50) default null,

Benke nchar (50) default null,

Birth date default null,

Rxtime date default null

) Engine = InnoDB default charset = utf8.

When connecting to MySQL in Java, you can set the character set in the connection statement. The syntax is as follows. Note that question marks are used to connect table names and attribute settings.

Conn = drivermanager. getconnection ("JDBC: mysql: // localhost: 3306/test? Useunicode = true & characterencoding = utf8 "," root "," syq ");

If you use the command line or IDE tool to directly execute SQL statements, if the query conditions contain Chinese characters, you should also set MySQL character encoding. The reason is as follows:

When MySQL processes connections, SQL requests sent from external connections are converted in the following order:
Character_set_client // character set used for customer connection
|
Character_set_connection // MySQL connection Character Set
|
Character_set_database // character set used by the database (Table, column)
|
Character_set_results // the character set used by the client to display

I. The root cause of garbled characters is:
1. the client does not correctly set the client Character Set, causing the original SQL statement to be converted to the character set referred to by connection. This conversion will lead to loss of information. If the client is in utf8 format, if it is converted to the gb2312 format, the information will be lost. Otherwise, the information will not be lost. Make sure that the character set of connection is greater than the client character set to ensure that no information is lost during conversion.
2. the font of the database is not correctly set. If the font of the database is incorrectly set, the connection character set is converted to the database character set and the encoding is still lost because it is the same as the above.

Setting method:

Modify these two parameters in my. ini or my. CNF.

[Mysqld]
Default-character-set = utf8
[MySQL]
Default-character-set = utf8

Reprint a webpage with Java coding problems

Java and UNICODE:

Java class files are UTF-8 encoded, And the JVM runtime uses UTF16

Java strings are unicode encoded.

In short, Java uses the Unicode character set to make it easier to internationalize.

 

Which character sets are supported by Java:

 

Which character sets can Java recognize and correctly process?

Check the charset class. The latest JDK supports 160 character sets. You can use the static availablecharsets method to obtain all Java-supported character sets.

Java code

Assertequals (160, charset. availablecharsets (). size (); set <string> charsetnames = charset. availablecharsets (). keyset (); asserttrue (charsetnames. contains ("UTF-8"); asserttrue (charsetnames. contains ("UTF-16"); asserttrue (charsetnames. contains ("gb2312"); asserttrue (charset. issupported ("UTF-8 "));

 

When do I need to pay attention to encoding?

 

1. read data from external resources:

This is related to the encoding method used by external resources. We need to use the character set used by external resources to read external data:

Java code

Inputstream is = new fileinputstream ("Res/input2.data"); inputstreamreader streamreader = new inputstreamreader (is, "gb18030 ");

We can see that we use gb18030 encoding to read external data. You can check the encoding of streamreader to verify that:

Java code

Assertequals ("gb18030", streamreader. getencoding ());

It is precisely because we have specified correct encoding for external resources that can be correctly decoded only when it is converted to a char array (gb18030-> Unicode ):

 

Java code

Char [] chars = new char [is. Available ()]; streamreader. Read (chars, 0, is. Available ());

But the code we often write is like the following:

Java code

Inputstream is = new fileinputstream ("Res/input2.data"); inputstreamreader streamreader = new inputstreamreader (is );

In this case, what encoding method does inputstreamreader use to read external resources? Unicode? No. At this time, the encoding method is the default JVM character set. This default character set is determined when the VM is started, usually based on the language environment and the charset of the underlying operating system. You can obtain the default JVM character set in the following ways:

Java code

Charset. defaultcharset ();

Why? Because we read data from external resources, and the encoding method of external resources is usually the same as the character set used by the operating system, this default method is understandable.

Okay, so I created a file through my ide ideas and read data from this file using the JVM default encoding method, but the read data is garbled. Why? The reason is that the files created through ideas are UTF-8 encoded. To get a default JVM-encoded file, create a TXT file manually.

 

2. Conversion between strings and byte Arrays

The following code converts a string to a byte array:

Java code

"String". getbytes ();

But have you noticed the encoding used for this conversion? In fact, the above Code is equivalent to the following:

Java code

"String". getbytes (charset. defaultcharset ());

That is to say, it converts a string into a byte array based on the default JVM encoding (instead of Unicode.

On the contrary, how do I create a string from a byte array?

Java code

New String ("string". getbytes ());

Similarly, this method uses the default Character Set of the platform to decode the specified array of bytes (here decoding refers to the conversion from a character set to Unicode ).

 

String encoding:

Java code

New String (input. getbytes ("ISO-8859-1"), "gb18030 ")

What does the above Code represent? Someone will say, "convert the input string from the ISO-8859-1 encoding method to the gb18030 encoding method ". If this statement is correct, how can we explain that the Java strings we just mentioned adopt unicode encoding?

This statement is not only inappropriate, but also a big mistake. Let's analyze it one by one. The fact is that we should use gb18030 encoding to read data and decode it into a string, but the result is encoded with a ISO-8859-1, resulting in an incorrect string. To recover the data, you must first restore the string to the original byte array, and then use the correct encoding gb18030 to re-Decode it into a string (that is, convert the data encoded in gb18030 to a unicode string ). Note that strings are always unicode encoded.

But the encoding conversion is not as simple as negative, here we can correctly convert back, because the ISO8859-1 is a single-byte encoding, so each byte is converted to string as is, that is, although this is an incorrect conversion, the encoding has not changed, so we still have the opportunity to convert the encoding back!

Summary:

Therefore, when dealing with Java coding problems, we should clearly distinguish three concepts: Java adopts the encoding: Unicode, JVM platform default Character Set and external resource encoding.

 

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.