Statement 接口的应用(存在sql语句的注入风险)(转)

实现简单的登录功能

复制代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCFindAll {
    
    private static final String jdbcName="com.mysql.jdbc.Driver";
    private static final String url="jdbc:mysql://127.0.0.1:3306/emp_dept";
    private static final String user="root";
    private static final String password="123456";
    /*
     * 一个类(DriverManeger)四个接口(Connection、PreparedStatement、ResultSet、Statement)
     * */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Connection conn=null;
        try {
            Class.forName(jdbcName);
            conn=DriverManager.getConnection(url, user, password);
            //登录的操作
            
            String usr="aaawfwfwfwfw' or 1 #"; //sql注入的风险
            String pwd="334343343434";
            
            String sql="select id,usr,pwd from user where usr='"+usr+"' and pwd='"+pwd+"'";
            Statement st=conn.createStatement();
            ResultSet rs=st.executeQuery(sql);
            if(rs.next()){
                System.out.println("登录成功!进入主页面!");
            }else{
                System.out.println("用户名或密码错误!登录失败!");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
复制代码

其中下面标红部分存在sql注入风险

在sql语句显示如下图:

查询结果如下图:(显示了所有的查询结果)

在这种情况下用户在不知道用户名和密码的情况下,轻易登录成功。所以不要用Statement 接口,用Preparedstatement接口。

原文地址:https://www.cnblogs.com/ty-v/p/8135850.html