Java连接MySQL时,字符集(Character Set)是指用于编码和解码字符的集合。在Java和MySQL之间传输数据时,确保字符集的一致性非常重要,以避免乱码问题。
常见的字符集包括:
在Java连接MySQL时,可以通过以下几种方式设置字符集:
String url = "jdbc:mysql://localhost:3306/mydatabase?useUnicode=yes&characterEncoding=UTF-8";
Connection conn = DriverManager.getConnection(url, "username", "password");
Properties props = new Properties();
props.setProperty("user", "username");
props.setProperty("password", "password");
props.setProperty("useUnicode", "yes");
props.setProperty("characterEncoding", "UTF-8");
String url = "jdbc:mysql://localhost:3306/mydatabase";
Connection conn = DriverManager.getConnection(url, props);
可以在MySQL的配置文件(如my.cnf
或my.ini
)中设置默认字符集:
[client]
default-character-set=UTF-8
[mysql]
default-character-set=UTF-8
[mysqld]
character-set-server=UTF-8
collation-server=UTF-8_general_ci
原因:
解决方法:
ALTER TABLE mytable CONVERT TO CHARACTER SET UTF-8 COLLATE UTF8_general_ci;
以下是一个完整的Java连接MySQL并设置字符集的示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MySQLConnectionExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase?useUnicode=yes&characterEncoding=UTF-8";
Properties props = new Properties();
props.setProperty("user", "username");
props.setProperty("password", "password");
try (Connection conn = DriverManager.getConnection(url, props)) {
System.out.println("Connected to the database!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
通过以上设置和方法,可以有效解决Java连接MySQL时字符集不一致导致的乱码问题。
领取专属 10元无门槛券
手把手带您无忧上云