mysql jdbc 中文乱码_Jdbc操作Mysql产生中文乱码的问题

以前用JDBC操作mysql是这样的:

/**

* 1.插入数据时jdbc写法:

*/

public static void main(String[] args) throws Exception {

//1.加载数据库驱动

Class.forName("com.mysql.jdbc.Driver");//括号里是:数据库驱动类的完全限定名

//2.获取数据库的连接

Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root","root");

/**

* 注意事项:Connection来自于java.sql.Connection;mydb是数据库名称;

* root分别是数据库连接的用户名和密码,3306是mysql的端口号。

*/

//3.获取PreparedStatement对象

String sql = "insert into t_user(username,address) values('韩','北京')";

//String sql = "insert into t_student(name) values('中文')";

PreparedStatement sta = con.prepareStatement(sql);

/**

* 注意事项:PreparedStatement来自于java.sql.PreparedStatemet

*/

//4.执行SQL语句

int rows = sta.executeUpdate();

if(rows > 0) {

System.out.println("操作成功!");

}

//释放资源

sta.close();

con.close();

/**

* 注意事项:要先关闭sta,再关闭con

*/

}

但是,今天不知道为什么就插入数据库的中文数据就变成了??

用这种方法再操作就不会出现中文乱码的问题:

public static void main(String[] args) throws Exception {

String hostip = "127.0.0.1";

String DBname = "mydb";

String user = "root";

String passwd = "root";

//1.加载数据库驱动

Class.forName("com.mysql.jdbc.Driver").newInstance();

//2.获取数据库的连接

Connection con=DriverManager.getConnection("jdbc:mysql://"+hostip +"/"+DBname+"?user="+user+"&password="+passwd+"&useUnicode=true&characterEncoding=utf-8");

//3.获取PreparedStatement对象

String sql = "insert into t_user(username,address) values('韩','北京')";

//String sql = "insert into t_student(name) values('中文')";

PreparedStatement sta = con.prepareStatement(sql);

/**

* 注意事项:PreparedStatement来自于java.sql.PreparedStatemet

*/

//4.执行SQL语句

int rows = sta.executeUpdate();

if(rows > 0) {

System.out.println("操作成功!");

}

//释放资源

sta.close();

con.close();

/**

* 注意事项:要先关闭sta,再关闭con

*/

}

可以参考下这篇关于中文乱码的文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值