Dbutils的QueryRunner無法通過中文查詢問題

l577217發表於2018-08-07

用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>

 查詢函式為:

	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>

可以得到正常結果,問題解決。 

 

相關文章