SQL语句由动态拼接而成,用户输入加入命令可能会导致SQL语意改变,如何防范?
解决方案 Connection
.preparedStatement(sql) (实现占位符)
PreparedStatement |
---|
.setInt |
.setString |
.setBoolean |
import java.sql.Statement;
public class HelloJDBC{
//数据库驱动
static final String JDBC_DRIVER = "";
static final String DB_URL ="";
static final String USER ="";
static final String PASSWORD ="";
public static void helloword() throws ClassNotFoundException(){
Connection conn = null;
PreparedStatement ptmt = null;
ResultSet rs = null;
//1.装载驱动程序
Class.forName(JDBC_DRIVER);
//2.建立数据库连接
try{
conn = DriverManager.getConnerction(DB_URL,USER,PASSWORD);
//3.执行SQL语句
ptmt = conn.prepareStatement("select * from user where userName = ? and password = ?");
ptmt.setString(1,userName);
ptmt.setString(2,password);
rs = ptmt.excuteQuery();
//4.获取执行结果
while(rs.next()){
user = new User();
user.setUserName(rs.getString("userName"));
user.setSex(rs.getBoolean("sex"));
}
}catch (SQLException e){
e.printStackTrace();
}finally(){
//5.清理环境
try{
if(conn != null)
conn.close();
if(ptmt != null)
ptmt.close()
if(rs != null)
rs.close()
}catch(SQLException e){
//ignore
}
}
return user;
}
}
}
|