一、Statement(存在SQL注入问题)
public static void main(String[] args) {
// login("lili","123");
login(" 'or' 1=1"," 'or' 1=1");
}
public static void login(String name,String pwd){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try{
conn = jdbcUtils.getConnection(); // 获取数据库连接
st = conn.createStatement(); // 获取SQL的执行对象
String sql="SELECT * FROM userinfo WHERE username='"+name+"' AND password='"+pwd+"';";
System.out.println(sql);
rs = st.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
System.out.println("======================");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,rs);
}
}
二、PreparedStatement(解决SQL注入问题)
public static void main(String[] args) {
// login("lili","123");
login("'' or 1=1","'' or 1=1");
}
public static void login(String name,String pwd){
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try{
conn = jdbcUtils.getConnection(); // 获取数据库连接
/*
prepareStatement 防止注入的本质,把传递过来的参数当做字符
假设集中存放转义字符,比如说 ' 会被直接转义
*/
String sql="SELECT * FROM userinfo WHERE username=? AND password=?";
st = conn.prepareStatement(sql); // 获取SQL的执行对象
st.setString(1,name);
st.setString(2,pwd);
rs = st.executeQuery(); // 查询完毕会返回一个结果集
while (rs.next()){
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
System.out.println("======================");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,rs);
}
}