Home >Java >Javagetting Started >Garbled characters appear when inserting Chinese data into mysql database in java

Garbled characters appear when inserting Chinese data into mysql database in java

王林
王林Original
2019-11-25 10:32:004895browse

Garbled characters appear when inserting Chinese data into mysql database in java

1. The first problem that needs to be eliminated when inserting Chinese garbled characters into the database is what is the default character set of MySQL and the corresponding character set of the database.

Usually for the sake of future compatibility , it is recommended to set the entire MySQL default character set to utf-8. You can use the following command to view the default character set:

mysql> SHOW VARIABLES LIKE 'character%';

It is recommended that for newly installed MySQL, you directly set all the default character sets to utf-8. For those that already have many databases, you can set the characters of specific databases separately. set.

Learning video recommendation: Zero basic introduction to java

Some setting methods about character sets:

Modify the settings of a specific database Character set

mysql>use mydb
mysql>alter database mydb character set utf-8;

Create a database and specify the character set of the database

mysql>create database mydb character set utf-8;

2. Specify JDBC to use utf-8 encoding during transmission

This way the entire program handles, The encoding format is unified for transmission and database storage, so Chinese will not be garbled. Therefore, the database URL corresponding to the Java program JDBC should be written in the following style:

 // 驱动程序名
    private static String driver = "com.mysql.jdbc.Driver";
    // URL指向要访问的数据库名
    private static String url = "jdbc:mysql://localhost:3306/watermarking?useUnicode=true&characterEncoding=utf-8";
    // MySQL配置时的用户名
    private static String user = "root";
    // MySQL配置时的密码
    private static String password = "root";

What follows the "?" in the URL specifies the use of UTF-8 for character encoding

More Please pay attention to java related articles: Introduction to java programming

The above is the detailed content of Garbled characters appear when inserting Chinese data into mysql database in java. For more information, please follow other related articles on the PHP Chinese website!

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