直接上代码:
- System.out.println(username+password);
- String sql = "select * from user where name =? and password =?";
- preparedStatement = connection.prepareStatement(sql);
- preparedStatement.setString(1,"中文乱码");
- preparedStatement.setString(2,password);
- System.out.println(preparedStatement.toString());
这样在后台输出sql语句是:com.mysql.jdbc.JDBC4PreparedStatement@5009ea: select * from user where name ='??' and password ='123'
中文是??。
解决方法:原因是设置datasource 的driver 时jdbc.url=jdbc:mysql://localhost:3306/shoppiong 没有指定编码
改成:
- private final static String URL = "jdbc:mysql://localhost/shoppingstyle=?characterEncoding=utf8";
这样在重新运行程序,后台输出sql语句为:com.mysql.jdbc.JDBC4PreparedStatement@c07125: select * from user where name ='张山' and password ='123'
解决了乱码问题
本文介绍了一种常见的MySQL数据库中出现的中文乱码问题及其解决方案。通过调整数据源连接字符串中的字符集参数,可以有效地避免SQL语句执行时出现中文乱码的情况。

被折叠的 条评论
为什么被折叠?



