用c3p0+Dbutils查询记录,c3p0配置文件为:
<property name="user">root</property>
<property name="password">123456</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///pri_lr</property>
(感谢id为【qq_36045418】的朋友提出的备注意见:配置文件中的 pri_lr 记得修改成自己的数据库名字)
查询函数为:
public User login(String name, String password) throws SQLException {
String sql = "select * from user where name=? and password=?";
return runner.query(sql, new BeanHandler<User>(User.class), name, password);
}
当查询的字段数据为中文时,查询结果为null,非中文则可以得到正常结果
UserService service = new UserService();
try {
List<User> users = service.qureyAll();
users.forEach(eachUser -> System.out.println(eachUser));
User user = service.login("张三", "123456");
System.out.println(user);
User userNotCh = service.login("asd", "123");
System.out.println(userNotCh);
} catch (SQLException e) {
e.printStackTrace();
}
输出结果:
User{id=1, name='张三', password='123456', gender='男'}
User{id=3, name='李四', password='123456', gender='女'}
User{id=4, name='王五', password='123456', gender='保密'}
User{id=5, name='asd', password='123', gender='男'}
null
User{id=5, name='asd', password='123', gender='男'}
字符编码的问题,表的编码为utf8
| user | CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`gender` enum('男','女','保密') DEFAULT '男',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
修改配置文件中的url为
<property name="jdbcUrl">jdbc:mysql:///pri_lr?characterEncoding=utf8</property>
可以得到正常结果,问题解决。