当前位置:网站首页>MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object

MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object

2022-07-06 08:26:00 Jatine

MySQL Learning record 11JDBCstatement object 、SQL Injection problems and PreparedStatement object

11.1statement object

Jdbc Medium statement Object to send... To the database SQL sentence , Want to complete the addition, deletion, modification and query of the database , You only need to send the add, delete, change and query statement to the database through this object .
Statement Object's executeUpdate Method , Used to send add... To the database 、 Delete 、 Changed sql sentence ,executeUpdate After the execution , Will return an integer ( That is, the number of rows affected ).
Statement.executeQuery Method is used to send query statements to the database ,executeQuery Method to return ResultSet object .

CRUD operation -create
Use executeUpdate(String sql) Method to complete the data adding operation , Example operation :

        Statement statement = connection.createStatement();
        String sql = "insert into user(... ) values(... . ) ";
        int num = statement.executeUpdate(sql);
        if (num > 0) {
    
            System.out.println(" Insert the success !!! ");
        }

CRUD operation -delete
Use executeUpdate(String sql) Method to delete data , Example operation :

        Statement statement = connection.createStatement();
        String sql = "delete from user where id = 1";
        int num = statement.executeUpdate(sql);
        if (num > 0) {
    
            System.out.println(" Delete successful !!! ");
        }

CRUD operation -update
Use executeUpdate(String sql) Method to complete the data modification operation , Example operation :

        Statement statement = connection.createStatement();
        String sql = "update user set name = '' where name = '' ";
        int num = statement.executeUpdate(sql);
        if (num > 0) {
    
            System.out.println(" Modification successful !!! ");
        }

CRUD operation -read
Use executeUpdate(String sql) Method to complete data query operation , Example operation :

        Statement statement = connection.createStatement();
        String sql = "select * from user where id = 1";
        ResultSet resultSet = statement.executeUpdate(sql);
        where(resultSet .next()){
    
        // Depending on the data type of the acquired column , Respectively called resultSet The corresponding method of mapping to java In the object 
        }

11.1.1 Code implementation ( Additions and deletions )

First write the database configuration file :

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456

Secondly, it is compiled jdbc Tool class :

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    

    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
    
        try {
    
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);

            // from db.properties Read these four information in 
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

            //1. The driver only loads once 
            Class.forName(driver);
        } catch (Exception e) {
    
            e.printStackTrace();
        }
    }

    // Get the connection 
    public static Connection getConnection() throws SQLException {
    
        return DriverManager.getConnection(url, username, password);
    }

    // Release the connection 
    public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
    
        if (rs != null) {
    
            rs.close();
        }
        if (st != null) {
    
            st.close();
        }
        if (conn != null) {
    
            conn.close();
        }
    }
}

Insert the test :

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestInsert {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 
            st = conn.createStatement();  // get SQL Execution object of 
            String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" +
                    "VALUES(4,'zhaoliu','123456','[email protected]','2020-01-01')";
            int i = st.executeUpdate(sql);  // hold sql Statement is thrown in and executed ,i Is the number of rows affected 
            if (i > 0) {
    
                System.out.println(" Insert the success !");
            }

        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

 Insert picture description here
View the results in the database table :
 Insert picture description here
Insert the success !
Now that the inserted code is successful , Then delete :

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestDelete {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 
            st = conn.createStatement();  // get SQL Execution object of 
            String sql = "DELETE FROM users WHERE id = 4";
            int i = st.executeUpdate(sql);  // hold sql Statement is thrown in and executed ,i Is the number of rows affected 
            if (i > 0) {
    
                System.out.println(" Delete successful !");
            }

        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

Can be observed , The only difference from inserting test code is sql sentence , At most, the prompt of successful modification operation , Nothing else needs to be changed .

Run code :
 Insert picture description here
View database table data :
 Insert picture description here
Delete successful !
Another update :

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestUpdate {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 
            st = conn.createStatement();  // get SQL Execution object of 
            String sql = "UPDATE users SET `NAME`='madongmei',`email`='[email protected]' WHERE id = 1;";
            int i = st.executeUpdate(sql);  // hold sql Statement is thrown in and executed ,i Is the number of rows affected 
            if (i > 0) {
    
                System.out.println(" The update is successful !");
            }

        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

 Insert picture description here
 Insert picture description here
The update is successful !

Inquire about :

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestSelect {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 
            st = conn.createStatement();  // get SQL Execution object of 

            String sql = "select * from users where id = 1";

            rs = st.executeQuery(sql);  // After the query, a result set will be returned 
            while (rs.next()) {
    
                System.out.println(rs.getString("NAME"));
            }
        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

 Insert picture description here

11.1.2SQL Injection problem

SQL Injection means web The application does not judge or filter the validity of the user's input data , Attackers can web Add extra... At the end of a predefined query statement in the application SQL sentence , Implement illegal operation without the administrator's knowledge , In this way, the database server is cheated to execute any unauthorized query , So we can get the corresponding data information .
SQL Injection is one of the most common network attacks , It's not using the operating system BUG To achieve an attack , It's about the negligence of programmers , adopt SQL sentence , Login without account , Even tampering with the database .

11.1.2.1SQL The general idea of injection attack

  • Look for SQL Injection location
  • Judge the server type and background database type
  • For different server and database characteristics SQL Injection attack

Case study :

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlInjection {
    
    public static void main(String[] args) {
    
        login("madongei", "123456");

    }

    public static void login(String username, String password) {
    
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 
            st = conn.createStatement();  // get SQL Execution object of 

            String sql = "select * from users where `NAME`='" + username + "' AND `PASSWORD` = '" + password + "'";

            rs = st.executeQuery(sql);  // After the query, a result set will be returned 
            while (rs.next()) {
    
                System.out.println(rs.getString("NAME"));
                System.out.println(rs.getString("PASSWORD"));
            }
        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            try {
    
                JdbcUtils.release(conn, st, rs);
            } catch (SQLException e) {
    
                e.printStackTrace();
            }
        }
    }
}

If you can log in normally , Then the user name should be output 、 Result of password
but :
 Insert picture description here
If you add the above code login("madongei", "123456"); Change it to login("'or '1=1","123456");
 Insert picture description here
All user names and passwords have been stolen .

11.2PreparedStatement object

prevent sql Injection and higher efficiency
1、 newly added

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.*;
import java.util.Date;

public class TestInsert {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 

            // difference   Use ? Instead of parameters 
            String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" + "VALUES(?,?,?,?,?)";
            st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute 

            // Assign parameters manually 
            st.setInt(1, 4);
            st.setString(2, "haha");
            st.setString(3, "123456");
            st.setString(4, "[email protected]");
            // Be careful  sql.Date
            // util.Date
            st.setDate(5, new java.sql.Date(new Date().getTime()));

            // perform 
            int i = st.executeUpdate();  // hold sql Statement is thrown in and executed ,i Is the number of rows affected 
            if (i > 0) {
    
                System.out.println(" Insert the success !");
            }

        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

 Insert picture description here
 Insert picture description here
2、 Delete

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class TestDelete {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 

            // difference   Use ? Instead of parameters 
            String sql = "delete from users where id = ?";
            st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute 

            // Assign parameters manually 
            st.setInt(1,4);

            // perform 
            int i = st.executeUpdate();  // hold sql Statement is thrown in and executed ,i Is the number of rows affected 
            if (i > 0) {
    
                System.out.println(" Delete successful !");
            }

        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

 Insert picture description here
 Insert picture description here
3、 to update

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestUpdate {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 

            // difference   Use ? Instead of parameters 
            String sql = "update users set `NAME` = ? where id = ?;";
            st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute 

            // Assign parameters manually 
            st.setString(1, "xialuo");
            st.setInt(2, 1);

            // perform 
            int i = st.executeUpdate();  // hold sql Statement is thrown in and executed ,i Is the number of rows affected 
            if (i > 0) {
    
                System.out.println(" The update is successful !");
            }

        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

 Insert picture description here
 Insert picture description here
4、 Inquire about

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.*;

public class TestSelect {
    
    public static void main(String[] args) throws SQLException {
    
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 

            // difference   Use ? Instead of parameters 
            String sql = "select * from users where id = ?";
            st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute 

            // Assign parameters manually 
            st.setInt(1, 1);

            // perform 
            rs = st.executeQuery();  // hold sql Statement is thrown in and executed ,i Is the number of rows affected 
            if (rs.next()) {
    
                System.out.println(rs.getString("NAME"));
            }

        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            JdbcUtils.release(conn, st, rs);
        }
    }
}

 Insert picture description here
5、 prevent sql Inject
Normal business :

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.*;

public class SqlInjection {
    
    public static void main(String[] args) {
    
        login("xialuo", "123456");

        //login("'or '1=1","123456");
    }

    public static void login(String username, String password) {
    
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 

            String sql = "select * from users where `NAME`=? AND `PASSWORD`=?";

            st = conn.prepareStatement(sql);  // precompile sql
            st.setString(1,username);
            st.setString(2,password);


            rs = st.executeQuery();  // After the query, a result set will be returned 
            while (rs.next()) {
    
                System.out.println(rs.getString("NAME"));
                System.out.println(rs.getString("PASSWORD"));
            }
        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            try {
    
                JdbcUtils.release(conn, st, rs);
            } catch (SQLException e) {
    
                e.printStackTrace();
            }
        }
    }
}

 Insert picture description here
Splicing sql:

import com.jatine.lesson02.utils.JdbcUtils;

import java.sql.*;

public class SqlInjection {
    
    public static void main(String[] args) {
    
        //login("xialuo", "123456");

        login("''or 1=1","123456");
    }

    public static void login(String username, String password) {
    
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
    
            conn = JdbcUtils.getConnection();  // Get database connection , So it's connected , Don't write those configurations anymore 

            String sql = "select * from users where `NAME`=? AND `PASSWORD`=?";

            st = conn.prepareStatement(sql);  // precompile sql
            st.setString(1,username);
            st.setString(2,password);


            rs = st.executeQuery();  // After the query, a result set will be returned 
            while (rs.next()) {
    
                System.out.println(rs.getString("NAME"));
                System.out.println(rs.getString("PASSWORD"));
            }
        } catch (SQLException e) {
    
            e.printStackTrace();
        } finally {
    
            try {
    
                JdbcUtils.release(conn, st, rs);
            } catch (SQLException e) {
    
                e.printStackTrace();
            }
        }
    }
}

 Insert picture description here
No results , There was no error

原网站

版权声明
本文为[Jatine]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131825406332.html