{ User user = null; try { QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource()); String sql = "select * from user where username=?"; user = queryRunner.query(sql, new BeanHandler<User>(User.class), username); if (user != null) { return "true"; } else { return "false"; } } catch (Exception e) { e.printStackTrace(); } return "none"; }将此段代码中的queryRunner替换
时间: 2024-02-14 13:21:24 浏览: 86
可以使用PreparedStatement对queryRunner进行替换,示例代码如下:
```
User user = null;
try {
Connection conn = DBUtils.getConnection();
String sql = "select * from user where username=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setAge(rs.getInt("age"));
// ...
}
rs.close();
ps.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
if (user != null) {
return "true";
} else {
return "false";
}
```
需要注意的是,此处需要手动关闭数据库连接,避免资源泄露。同时,代码中也需要手动从ResultSet中读取数据,再赋值给User对象,相对于BeanHandler来说,代码量稍微多一些。
阅读全文