总结 PreparedStatement解决sql注入问题
:sql中使用?做占位符
2.得到PreparedStatement对象
PreparedStatement pst=conn.prepareStatement(String sql);
pst.setString(1,"aaa");//设置 第一个?的占位符赋值
pst.setString(2,"bbb");
// 查找用户 使用PreparedStatement 解决了 sql注入问题
public
User findUser(User user) {
String sql =
"select * from user where username='?' and password='?'"
;
Connection conn =
null
;
PreparedStatement pst =
null
;
ResultSet rs =
null
;
try
{
conn = jdbcUtils. getConnection();
pst = conn.prepareStatement(sql);
pst.setString(1, user.getUsername());
pst.setString(2, user.getPassword());
rs = pst.executeQuery();
if
(rs.next()) {
User u =
new
User();
u.setId(rs.getInt(
"id"
));
u.setUsername(rs.getString(
"username"
));
u.setPassword(rs.getString(
"password"
));
u.setEmail(rs.getString(
"email"
));
return
u;
}
}
catch
(Exception e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
return
null
;
}
|