且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过JDBC接口将UTF-8字符串正确写入MySQL

更新时间:2023-11-27 15:39:58

确保您的 MySQL 配置编码被正确定义.使用以下命令检查您的设置和修改的正确性:

Ensure that your MySQL configuration encoding is defined correctly. Check your settings and the correctness of the modifications with these commands:

show variables like 'character%';

显示变量,如 'collat​​ion%';

将这些行添加到 my.cnfmy.ini:

Add these lines to either my.cnf or my.ini:

对于 MySQL 5.1.nn 和更高版本 5.5.29,您只需要这两行:

For MySQL 5.1.nn, and later versions 5.5.29 you just need these two lines:

[mysqld]
character-set-server = utf8
character-set-filesystem = utf8

对于 MySQL 5.0.nn 及更早版本,请使用以下设置:

For MySQL 5.0.nn and older use these settings:

[client]
default-character-set=utf8


[mysql]
default-character-set=utf8


[mysqld]
default-character-set=utf8
character-set-server=utf8

使用 MySQL-Workbench 进行设置可能更方便.5+ 版本非常好.

It is probably more convenient to use MySQL-Workbench for your settings. Versions 5+ are excellent.

在你的 Java 程序中像这样连接:

In your Java program connect like this:

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&characterEncoding=UTF-8","user","passwd");