-
SQL注入
SQL注入即是指web应用程序对用户输入数据的合法性没有判断或过滤不严, 攻击者可以在web应用程序中事先定义好的查询语句的结尾上添加额外的SQL语句, 在管理员不知情的情况下实现非法操作, 以此来实现欺骗数据库服务器执行非授权的任意查询, 从而进一步得到相应的数据信息。 该问题存在于Statement接口中 在它的子接口PreparedStatement中该问题得到了解决 那我们就在使用Statement接口的情况下展示sql注入
-
原表数据
-
根据账户密码查询该人信息
package com.mystudy.jdbc;
import java.sql.*;
public class SqlInject {
public static void login(String username,String password) throws ClassNotFoundException, SQLException {
//forName抛出异常 ClassNotFoundException
Class.forName("com.mysql.jdbc.Driver");
//getConnection 抛出异常SQLException
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test1?useSSL=true","root","root");
Statement st=conn.createStatement();
String sql ="SELECT * FROM student where stu_user='"+username+"' and stu_password='"+password+"'";
ResultSet rs=st.executeQuery(sql);
while (rs.next()){
System.out.print(rs.getInt(1));
System.out.print(rs.getString(2));
System.out.print(rs.getString(3));
System.out.print(rs.getDate(4));
System.out.print(rs.getString(5));
System.out.println(rs.getString(6));
}
//资源释放
rs.close();
st.close();
conn.close();
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
login("hhh","123456");
}
}
结果:
- sql注入情况
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//login("hhh","123456");
login("'or'1=1", "'or'1=1");
}
结果:盗出了所有用户信息
代码解释:
- 正常情况下:
"SELECT * FROM student where stu_user='"+username+"' and stu_password='"+password+"'"
将login("hhh","123456");
带入
"SELECT * FROM student where stu_user='hhh' and stu_password='123456'"
- sql注入情况登录:
"SELECT * FROM student where stu_user='"+username+"' and stu_password='"+password+"'"
将login("'or'1=1", "'or'1=1");
带入
"SELECT * FROM student where stu_user=''or'1=1' and stu_password=''or'1=1'"
- 这里建议再学习一下事务回滚:事务回滚
- 这里有JDBC的入门学习流程:入门学习流程