public class JDBCDemo3 {
public static void demo3_1(){
boolean flag=login("aaa' OR ' ","1651561"); //若已知用戶名,用這種方式便可不用知道密碼就可登陸成功
if (flag){
System.out.println("登陸成功");
}else{
System.out.println("登陸失敗");
}
}
public static boolean login(String username,String password){
Connection conn=null;
Statement stat=null;
ResultSet rs=null;
boolean flag=false;
try {
conn=JDBCUtils.getConnection();
String sql="SELECT * FROM user WHERE username='"+username+"'AND password='"+password+"'"; //此處是SQL注入漏洞的關(guān)鍵,因為是字符串的拼接,會使查詢語句變?yōu)椋篠ELECT * FROM user WHERE username='aaa' OR '' AND password='1651561',此查詢語句是可得到結(jié)果集的,便出現(xiàn)此漏洞
stat=conn.createStatement();
rs=stat.executeQuery(sql);
if(rs.next()){
flag=true;
}else{
flag=false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public static void demo3_1(){
boolean flag=login1("aaa' OR ' ","1651561");
if (flag){
System.out.println("登陸成功");
}else{
System.out.println("登陸失敗");
}
}
public static boolean login1(String username,String password){
Connection conn=null;
PreparedStatement pstat=null;
ResultSet rs=null;
boolean flag=false;
try {
conn=JDBCUtils.getConnection();
String sql="SELECT * FROM user WHERE username=? AND password=?"; //使用?代替參數(shù),預(yù)先設(shè)置好sql格式,就算在輸入sql關(guān)鍵字也不會被sql識別
pstat=conn.prepareStatement(sql);
pstat.setString(1,username); //設(shè)置問號的值
pstat.setString(2,password);
rs=pstat.executeQuery();
if(rs.next()){
flag=true;
}else{
flag=false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
}