search
HomeDatabaseMysql Tutorialjdbc mysql 中文乱码的解决方法

jdbc mysql 中文乱码的解决方法

Jun 07, 2016 pm 03:02 PM
jdbcmysqlChineseGarbled charactersmethodsolvepass

通过jdbc 连接mysql 数据库的实例,以及中文乱码的解决方法: import java.sql.*;/** * 使用JDBC连接数据库MySQL的过程: * DataBase: db_test * tables: tab_test; * username: user_test; * passwd: passwd_test; * * @author zhongbo.wzb@alibaba-inc.com

通过jdbc 连接mysql 数据库的实例,以及中文乱码的解决方法:

import java.sql.*;

/**
 * 使用JDBC连接数据库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 {
    // 第一步:加载MySQL的JDBC的驱动
    Class.forName("com.mysql.jdbc.Driver");

    //取得连接的url,能访问MySQL数据库的用户名:user_test;密码:passwd_test, 数据库名: db_test
    String url = "jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8";
    String username = "user_test";
    String password = "passwd_test";

    // 第二步:创建与MySQL数据库的连接类的实例
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

  public static void main(String args[]) {
    System.out.println("args num: " + args.length);
    for (int i = 0; i 

<p><span>不</span><span><span>过,官方文档还说,"要想覆盖客户端上的自动检测编码功能,可在用于连接到服务器的URL中使用“characterEncoding”属性。" </span></span><br>
</p>
<p><span><span><br>
</span></span></p>
<p><span><span><span>解决方法二: </span><br>
<br>
<span>连接mysql时(无论在从mysql读还是取数据的情况),指定使用的编码方式为utf-8,具体代码如下 </span><br>
<br>
<span>//装载mysql-jdbc驱动 </span><br>
<br>
<span>Class.forName("com.mysql.jdbc.Driver").newInstance(); </span><br>
<br>
<span>//连接数据库 </span><br>
<br>
<span>Connection sqlCon = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?                         user=root&password=1&useUnicode=true&characterEncoding=utf-8"
 ); </span><br>
</span></span></p>
<br>
<p><br>
</p>
<p><br>
</p>
<p><br>
</p>
<p><br>
</p>
<p><br>
</p>
<p><span>charset 和 collation 有多个级别的设置:服务器级、数据库级、表级、列级和连接级</span><br>
<br>
<span>1.服务器级 </span><br>
<span>  查看设置:show global variables like 'character_set_server'; 和 show global variables like 'collation_server';</span><br>
<span>  修改设置:在OPTION FILE (/etc/mysql/my.cnf)里设置: </span><br>
<span>   [mysqld] </span><br>
<span>    character_set_server=utf8 </span><br>
<span>    collation_server=utf8_general_ci </span><br>
<br>
<span>2. 数据库级 </span><br>
<span>   查看设置:select * from information_schema.schemata where schema_name = 'cookbook';</span><br>
<span>   设置: </span><br>
<span>     1.若没有显式设置,则自动使用服务器级的配置 </span><br>
<span>     2.显式设置:在创建库时指定 </span><br>
<span>       create database playUtf8  DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;</span><br>
<br>
<span>3.表级 </span><br>
<span>   查看设置:show create table course; </span><br>
<span>   设置: </span><br>
<span>     1.若没有显式设置,则自动使用数据库级的配置 </span><br>
<span>     2.显式设置:在创建表时指定 </span><br>
<span>       create table utf ( id int ) default charset=utf8 default collate=utf8_bin;</span><br>
<br>
<span>4.列级 </span><br>
<span>   查看设置:show create table course; </span><br>
<span>   设置: </span><br>
<span>     1.若没有显式设置,则自动使用表级的配置 </span><br>
<span>     2.显式设置: </span><br>
<br>
<span>     CREATE TABLE Table1(column1 VARCHAR(5) CHARACTER SET latin1 COLLATE latin1_german1_ci);</span><br>
<br>
<span>5.连接级别 </span><br>
<span>  查看设置: </span><br>
<span>     show variables like 'character_set_client';  # 服务端使用这个编码来理解客户端发来的statements </span><br>
<span>     show variables like 'character_set_connection' ; # 我还不知道什么意思,等看了mysql源码再说 </span><br>
<span>     show variables like 'character_set_results'; # 服务端使用这个编码回送结果集和错误信息 </span><br>
<span>  设置: </span><br>
<span>     客户端在连接时可以指定这些参数;同时,服务端也提供了一个Global范围的值,客户端未指定这些参数时,服务端就使用这个Global值。这个global值怎么设置的? 我查遍了很多文档,似乎还没看到设置的办法 (有人说通过my.cnf,或者在启动mysqld时指定命令行参数,其实都是错的)</span><br>
<br>
<span>   </span><br>
<br>
<span>附:connector/j传输SQL时用什么编码? </span><br>
<span>  答案: "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."</span><br>
<span>   也就是说,是在连接时查询服务器端的character_set_server值,再确定连接将使用的编码。 </span><br>
<span>   不</span><span><span>过,官方文档还说,"要想覆盖客户端上的自动检测编码功能,可在用于连接到服务器的URL中使用“characterEncoding”属性。" </span></span><br>
</p>
<p><span><span><br>
</span></span></p>
<p><span><span><span>解决方法二: </span><br>
<br>
<span>连接mysql时(无论在从mysql读还是取数据的情况),指定使用的编码方式为utf-8,具体代码如下 </span><br>
<br>
<span>//装载mysql-jdbc驱动 </span><br>
<br>
<span>Class.forName("com.mysql.jdbc.Driver").newInstance(); </span><br>
<br>
<span>//连接数据库 </span><br>
<br>
<span>Connection sqlCon = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?                         user=root&password=1&useUnicode=true&characterEncoding=utf-8"
 ); </span><br>
<br>
<br>
</span></span></p>


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools