该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
import java.sql.*;
import org.junit.Test;
/**
* 测试sql注入问题
* @author Wangjianyu
*
*/
public class TextLogin {
@Test
public void testLogin() {
try {
login("23'or'23","2322");
login2("23","2322");
login2("23'or'23","2322");
login("23","2322");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用户登陆方法1
* @param username
* @param password
* @throws Exception
*/
public void login(String username,String password) throws Exception {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/web08?serverTimezone=UTC","root","748159263");
//创建执行sql语句的对象
Statement stmt=conn.createStatement();
//书写一个SQL语句
String sql="select * from tbl_user where "+"uname='"+username+"' and upassword='"+password+"'";
//执行sql语句
ResultSet rs=stmt.executeQuery(sql);
//对结果集进行处理
if(rs.next()) {
System.out.println("登录"+username+"成功");
System.out.println(sql);
}else {
System.out.println("账号或密码错误");
}
if(rs!=null) {
rs.close();
}
if(stmt!=null) {
stmt.close();
}
if(conn!=null) {
conn.close();
}
}
//使用预编译说明
public void login2(String username,String password) throws Exception {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/web08?serverTimezone=UTC","root","748159263");
//编写sql语句
String sql="select * from tbl_user where uname=? and upassword=?";
//创建预处理对象
PreparedStatement pstmt=conn.prepareStatement(sql);
//设置参数(给占位符)
pstmt.setString(1,username);
pstmt.setString(1,password);
//执行查询操作
ResultSet rs=pstmt.executeQuery(sql);
//对结果集进行处理
if(rs.next()) {
System.out.println("登录"+username+"成功");
System.out.println(sql);
}else {
System.out.println("账号或密码错误");
}
if(rs!=null) {
rs.close();
}
if(pstmt!=null) {
pstmt.close();
}
if(conn!=null) {
conn.close();
}
}
}