import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class preparedStamentDemo {
public boolean login(String usename,String password) throws ClassNotFoundException, SQLException{
String className="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/数据库的名称";
String sqluse="root";
String sqlpassword="密码";
Class.forName(className);
Connection con=DriverManager.getConnection(url, sqluse, sqlpassword);
Statement sta=con.createStatement();
String sql="select *from D_user where username= '"+ usename+" and `password`= '"+password;
System.out.println(sql);
ResultSet rSet=sta.executeQuery(sql);
return rSet.next();//返回结果判断用户名和密码是否和数据库的相对应
}
@Test
public void cc() throws ClassNotFoundException, SQLException {
String uString="ni' or 'ni'='ni'";//上面输出的为select *from D_user where username= 'ni' or 'ni'='ni' and `password`= 'ni' or 'ni'='ni'
String pString="ni' or 'ni'='ni'";//上面输出的为select *from D_user where username= 'ni' or 'ni'='ni' and `password`= 'ni' or 'ni'='ni'
boolean a=login(uString, pString);
System.out.println(a);//输出为恒定为true
}
//当别人恶意输入 ni' or 'ni'='ni'将会导致输出全部为ture 使得sql失去了本应该有的效果
//解决方法,可以先对数据进行校验,把用户名中的= ‘ 这些东西拿出来在进行校验 也可以使用以下的方法
}
public boolean login2(String usename,String password) throws ClassNotFoundException, SQLException{
String className="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/数据库的名称";
String sqluse="root";
String sqlpassword="密码";
Class.forName(className);
Connection con=DriverManager.getConnection(url, sqluse, sqlpassword);
String sql ="select *from T_user where username=? and password=?";
PreparedStatement stamentDemo=con.prepareStatement(sql);
stamentDemo.setString(1,usename);
stamentDemo.setString(2,password);//如果少一个异常会抛出异常,或者多一个都会抛出异常
ResultSet rSet=stamentDemo.executeQuery();
System.out.println(sql);//输出为 select *from T_user where username=? and password=?
return rSet.next();
}
//得到的结果为false,有效的避免了sql的恶意攻击。