直接上代码:
- 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'
解决了乱码问题