jdbc插入mysql中文乱码的问题

kgblue kgblue 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
public class Test {

public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String connStr = "jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=UTF-8";
String dbUser = "root";
String dbPassword = "123456";
conn = DriverManager.getConnection(connStr, dbUser, dbPassword);
if (conn != null) {
System.out.println("连接成功");
stat = conn.createStatement();
stat.execute("drop database test_db");
stat.execute("create database test_db CHARACTER SET UTF8");
stat.execute("use test_db");
stat.execute("create table if not exists test_info( role_id int primary key auto_increment, role_name varchar(50) not null)default charset=UTF8");
stat.execute("insert into test_info(role_name) values ('测试')");
rs = stat.executeQuery("select * from test_info");
while (rs.next()) {
System.out.println(rs.getInt("role_id")+" : "+rs.getString("role_name"));
}
} else {
System.out.println("连接失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
stat.close();
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
麻烦兄弟们看看,为什么上面一段代码查询出来的会是乱码呢?我在数据库中查询也是乱码。我数据库使用的编码是UTF-8的,连接字符串、数据库、表,都是使用的UTF-8。
...全文
评论 4
收藏 已收藏
分享
返回顶部
kgblue
Java 51,407 成员 86,130 内容