Connect to an instance of the mysql database through jdbc, and solve the problem of Chinese garbled characters: importjava. SQL. *; * use JDBC to connect to MySQL: * DataBase: db_test * tables: tab_test; * username: user_test; * passwd: passwd_test; ** @ authorzhongbo.wzb@alibaba-inc.com
Connect to an instance of the mysql database through jdbc, and solve the problem of Chinese garbled characters: import java. SQL. *;/*** use JDBC to connect to MySQL: * DataBase: db_test * tables: tab_test; * username: user_test; * passwd: passwd_test; ** @ author zhongbo.wzb@alibaba-inc.com
Connect to the mysql database instance through jdbc and solve the Chinese garbled characters:
Import java. SQL. *;/*** use JDBC to connect to MySQL: * DataBase: db_test * tables: tab_test; * username: user_test; * passwd: passwd_test; ** @ author zhongbo.wzb@alibaba-inc.com */public class DBTest {public static Connection getConnection () throws SQLException, ClassNotFoundException {// Step 1: load the JDBC Driver Class of MySQL. forName ("com. mysql. jdbc. driver "); // get the connection url. The username that can access the MySQL database: user_test; Password: passwd_test, database Name: db_test String url = "jdbc: mysql: // localhost: 3306/db_test? UseUnicode = true & characterEncoding = UTF-8 "; String username =" user_test "; String password =" passwd_test "; // Step 2: create an instance Connection conn = DriverManager for the Connection class with the MySQL database. getConnection (url, username, password); return conn;} public static void main (String args []) {System. out. println ("args num:" + args. length); for (int I = 0; I <args. length; I ++) {System. out. println ("arg" + I + ":" + args [I]);} Co Nnection conn = null; Statement statement = null; try {// Step 3: Obtain the connection class instance con and use con to create the Statement object class instance SQL _statement conn = getConnection (); statement = conn. createStatement ();/* String SQL _update = "insert into tab_test (province, num, timestamp)" + "values ('shandong ', 2, '2017-04-18 00:00:00 '); "; System. out. println (SQL _update); statement.exe cuteUpdate (SQL _update); * // Step 4: Execute the query. Use the ResultSet class object to return the query result Strin. G query = "select * from tab_test;"; ResultSet result = statement.exe cuteQuery (query); while (result. next () {System. out. print (result. getInt (1) + "\ t |"); System. out. print (result. getString (2) + "\ t |"); System. out. print (result. getInt (3) + "\ t |"); System. out. println (result. getString (4) ;}} catch (ClassNotFoundException e) {System. err. print ("ClassNotFoundException:" + e. getMessage (); e. pri NtStackTrace (); System. exit (1);} catch (SQLException e) {System. err. println ("SQLException:" + e. getMessage (); e. printStackTrace (); System. exit (1);} catch (Exception e) {System. err. print ("Exception:" + e. getMessage (); e. printStackTrace (); System. exit (1) ;}finally {// release resources; try {if (statement! = Null) {statement. close (); statement = null;} if (conn! = Null) {conn. close (); conn = null ;}} catch (SQLException e) {System. err. println ("SQLException:" + e. getMessage (); e. printStackTrace (); System. exit (1);} catch (Exception e) {System. err. println ("Exception:" + e. getMessage (); e. printStackTrace (); System. exit (1 );}}}}
However, the official document also says, "to override the automatic detection encoding function on the client, you can use the" characterEncoding "attribute in the URL used to connect to the server. "
Solution 2:
When connecting to mysql (whether reading data from mysql or retrieving data), specify the UTF-8 encoding method. The specific code is as follows:
// Load the mysql-jdbc driver
Class. forName ("com. mysql. jdbc. Driver"). newInstance ();
// Connect to the database
Connection sqlCon = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/test? User = root & password = 1 & useUnicode = true & characterEncoding = UTF-8 ");
Charset and collation have multiple levels of settings: Server-level, database-level, table-level, column-level, and connection-level.
1. Server-level
View settings: show global variables like 'character _ set_server '; and show global variables like 'collation _ Server ';
Modify settings: In option file (/etc/mysql/my. cnf), set:
[Mysqld]
Character_set_server = utf8
Collation_server = utf8_general_ci
2. Database-level
View settings: select * from information_schema.schemata where schema_name = 'cookbook ';
Settings:
1. If no explicit settings are available, server-level configuration is automatically used.
2. Explicit settings: Specify
Create database playUtf8 default character set latin1 COLLATE latin1_swedish_ci;
3. Table-level
View settings: show create table course;
Settings:
1. If no explicit settings are available, the database-level configuration is automatically used.
2. Explicit settings: Specify
Create table utf (id int) default charset = utf8 default collate = utf8_bin;
4. Column-level
View settings: show create table course;
Settings:
1. If no explicit settings are available, table-level configuration is automatically used.
2. Explicit settings:
Create table Table1 (column1 VARCHAR (5) character set latin1 COLLATE latin1_german1_ci );
5. Connection level
View settings:
Show variables like 'character _ set_client '; # The server uses this encoding to understand the statements sent by the client.
Show variables like 'character _ set_connection '; # I don't know what it means. Let's wait until I read the mysql source code.
Show variables like 'character _ set_results '; # The server uses this encoding to return the result set and error message.
Settings:
The client can specify these parameters during connection. At the same time, the server also provides a Global value. If the client does not specify these parameters, the server uses this Global value. How do I set this global value? I have checked many documents and it seems that I haven't seen the setting method (Some people say that it is wrong to specify the command line parameter when I use my. cnf or when I start mysqld)
Appendix: What encoding does connector/j use to transmit SQL statements?
Answer: "The character encoding between client and server is automatically detected upon connection. The encoding used by the driver is specified on the server using the character_set_server system variable for server versions 4.1.0 and newer ."
That is to say, it is to query the character_set_server value of the server during the connection, and then determine the encoding used by the connection.
However, the official document also says, "to override the automatic detection encoding function on the client, you can use the" characterEncoding "attribute in the URL used to connect to the server. "
Solution 2:
When connecting to mysql (whether reading data from mysql or retrieving data), specify the UTF-8 encoding method. The specific code is as follows:
// Load the mysql-jdbc driver
Class. forName ("com. mysql. jdbc. Driver"). newInstance ();
// Connect to the database
Connection sqlCon = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/test? User = root & password = 1 & useUnicode = true & characterEncoding = UTF-8 ");