当前位置:网站首页>Younger sister Juan takes you to learn JDBC -- two days' Sprint Day2

Younger sister Juan takes you to learn JDBC -- two days' Sprint Day2

2022-06-26 05:57:00 Beijing and JIUPU

Sister Juan will take you to learn jdbc—2 Sky sprint Day2

 Insert picture description here

Blog home page : The blog home page of Beijing and JIUPU

Welcome to pay attention to the likes and comments

This article is original by Beijing and JIUPU ,csdn First episode !

Series column :java Study

Reference Online Course : Power nodes

Starting time :2022 year 6 month 21 Japan

You do march and April , There will be an answer in August and September , Come on

If you think the blogger's article is good , Please support the blogger for the third company

Last words , The author is a newcomer , Not doing well in many ways , Welcome the boss to correct , Study together , To rush
Recommend a simulated interview 、 Brush Title artifact Click to enter the website

The problem exists BUG

user name :fdsa

password :fdsa’ or ‘1’='1 Login successful

This phenomenon is called SQL Inject ( Safe hidden trouble ).( Hackers often use )5、 Lead to SQL What is the root cause of Injection ?

The information entered by the user contains sql Keyword of statement , And these keywords participate in sql Statement compilation process , Lead to sql The original meaning of the statement is distorted , And then achieve SQL Inject .


package com.bjpowernode.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*  Realization function : 1、 demand :  Simulate the realization of user login function . 2、 Business description :  While the program is running , Provide an entry for input , It allows users to enter a user name and password   After the user enters the user name and password , Submission of information ,java The program collects user information  Java The program connects to the database to verify whether the user name and password are legal   legal : Show login success   illegal : Show login failure  3、 Data preparation :  In actual development , Table design will use professional modeling tools , Let's install a modeling tool here :PowerDesigner  Use PD Tools to design database tables .( See user-login.sql Script ) 4、 There are problems with the current program :  user name :fdsa  password :fdsa' or '1'='1  Login successful   This phenomenon is called SQL Inject ( Safe hidden trouble ).( Hackers often use ) 5、 Lead to SQL What is the root cause of Injection ?  The information entered by the user contains sql Keyword of statement , And these keywords participate in sql Statement compilation process ,  Lead to sql The original meaning of the statement is distorted , And then achieve sql Inject . */
public class JDBCTest06 {
    
    public static void main(String[] args) {
    
        //  Initialize an interface 
        Map<String,String> userLoginInfo = initUI();
        //  Verify user name and password 
        boolean loginSuccess = login(userLoginInfo);
        //  Final output 
        System.out.println(loginSuccess ? " Login successful " : " Login failed ");
    }/** *  The user login  @param userLoginInfo  User login information  * @return false It means failure ,true It means success  / private static boolean login(Map<String, String> userLoginInfo) { //  Marking consciousness  boolean loginSuccess = false; //  Define variables separately  String loginName = userLoginInfo.get("loginName"); String loginPwd = userLoginInfo.get("loginPwd"); // JDBC Code  Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // 1、 Registration drive  Class.forName("com.mysql.jdbc.Driver"); // 2、 Get the connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode", "root", "333"); // 3、 Get database operation object  stmt = conn.createStatement(); // 4、 perform sql String sql = "select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'"; //  The above is just finished sql Statement splicing , The following code means , send out sql Sentence to DBMS,DBMS Conduct sql compile . //  Just put the user provided “ Illegal information ” Compile it . Led to the original sql The meaning of the sentence is distorted . rs = stmt.executeQuery(sql); // 5、 Processing result set  if(rs.next()){ //  Login successful  loginSuccess = true; } } catch (Exception e) { e.printStackTrace(); } finally { // 6、 Release resources  if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return loginSuccess; } ​ /** *  Initialize the user interface  @return  Login information such as user name and password entered by the user  */
         private static Map<String, String> initUI() {
    
     Scanner s = new Scanner(System.in);

     System.out.print(" user name :");
     String loginName = s.nextLine();

     System.out.print(" password :");
     String loginPwd = s.nextLine();

     Map<String,String> userLoginInfo = new HashMap<>();
     userLoginInfo.put("loginName", loginName);
     userLoginInfo.put("loginPwd", loginPwd);

     return userLoginInfo;
         }


}

solve SQL Injection problem

3、 solve SQL What is the key to injection ?

Even if the information provided by the user contains sql Keyword of statement , But these keywords are not involved in compiling . It doesn't work .4、 Compare the statement and Preparedstatement?

Statement There is sql Injection problem ,Preparedstatement It's solved SQL Injection problem .

Statement It's compile once, execute once .PreparedStatement Is compiled once , Multiple executions .Preparedstatement More efficient .Preparedstatement Type security checks will be done at the compilation stage .

package com.bjpowernode.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/** *  author : Du Jubin  * * 1、 solve SQL Injection problem ? *  As long as the information provided by users is not involved SQL Statement compilation process , The problem is solved . *  Even if the information provided by the user contains SQL Keyword of statement , But did not participate in the compilation , It doesn't work . *  If user information is not involved SQL Statement compilation , Then you have to use java.sql.PreparedStatement * PreparedStatement Interface inherited java.sql.Statement * PreparedStatement Is a precompiled database operation object . * PreparedStatement The principle is : In advance of SQL Statement , And then to SQL Statement transmission “ value ”. * 2、 test result : *  user name :fdas *  password :fdsa' or '1'='1 *  Login failed  * 3、 solve SQL What is the key to injection ? *  Even if the information provided by the user contains sql Keyword of statement , But these keywords are not involved in compiling . It doesn't work . * 4、 Compare the Statement and PreparedStatement? * - Statement There is sql Injection problem ,PreparedStatement It's solved SQL Injection problem . * - Statement It's compile once, execute once .PreparedStatement Is compiled once , Executable N Time .PreparedStatement More efficient . * - PreparedStatement Type security checks will be done at the compilation stage . * *  in summary :PreparedStatement More use . There are very few cases where Statement * 5、 Under what circumstances must Statement Well ? *  Business requirements must support SQL At the time of Injection . * Statement Support SQL Inject , All business requirements require sql Statement splicing , You have to use Statement. */
public class JDBCTest07 {
    
    public static void main(String[] args) {
    
        //  Initialize an interface 
        Map<String,String> userLoginInfo = initUI();
        //  Verify user name and password 
        boolean loginSuccess = login(userLoginInfo);
        //  Final output 
        System.out.println(loginSuccess ? " Login successful " : " Login failed ");
    }

    /** *  The user login  * @param userLoginInfo  User login information  * @return false It means failure ,true It means success  */
    private static boolean login(Map<String, String> userLoginInfo) {
    
        //  Marking consciousness 
        boolean loginSuccess = false;
        //  Define variables separately 
        String loginName = userLoginInfo.get("loginName");
        String loginPwd = userLoginInfo.get("loginPwd");

        // JDBC Code 
        Connection conn = null;
        PreparedStatement ps = null; //  Use here PreparedStatement( Precompiled database operation object )
        ResultSet rs = null;

        try {
    
            // 1、 Registration drive 
            Class.forName("com.mysql.jdbc.Driver");
            // 2、 Get the connection 
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode", "root", "333");
            // 3、 Get the precompiled database operation object 
            // SQL Frame of statement . One of them ?, Represents a placeholder , One ? Receive one in the future “ value ”, Be careful : Placeholders cannot be enclosed in single quotes .
            String sql = "select * from t_user where loginName = ? and loginPwd = ?";
            //  The program executes here , Will send sql Give the sentence box to DBMS, then DBMS Conduct sql Precompiled statements .
            ps = conn.prepareStatement(sql);
            //  Give placeholder ? Pass value ( The first 1 A question mark subscript is 1, The first 2 A question mark subscript is 2,JDBC All subscripts in are from 1 Start .)
            ps.setString(1, loginName);
            ps.setString(2, loginPwd);
            // 4、 perform sql
            rs = ps.executeQuery();
            // 5、 Processing result set 
            if(rs.next()){
    
                //  Login successful 
                loginSuccess = true;
            }
        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            // 6、 Release resources 
            if (rs != null) {
    
                try {
    
                    rs.close();
                } catch (SQLException e) {
    
                    e.printStackTrace();
                }
            }
            if (ps != null) {
    
                try {
    
                    ps.close();
                } catch (SQLException e) {
    
                    e.printStackTrace();
                }
            }
            if (conn != null) {
    
                try {
    
                    conn.close();
                } catch (SQLException e) {
    
                    e.printStackTrace();
                }
            }
        }
        return loginSuccess;
    }

    /** *  Initialize the user interface  * @return  Login information such as user name and password entered by the user  */
    private static Map<String, String> initUI() {
    
        Scanner s = new Scanner(System.in);

        System.out.print(" user name :");
        String loginName = s.nextLine();

        System.out.print(" password :");
        String loginPwd = s.nextLine();

        Map<String,String> userLoginInfo = new HashMap<>();
        userLoginInfo.put("loginName", loginName);
        userLoginInfo.put("loginPwd", loginPwd);

        return userLoginInfo;
    }
}

demonstration statement Use of

When to use statement

in summary : Preparedstatement More use . There are very few cases where statement5、 Under what circumstances must statement Well ?

Business requirements must support sql At the time of Injection .

statement Support sql Inject , All business requirements require sql Statement splicing , You have to use statement.

package ustc.java.jdbc;

import java.sql.*;
import java.util.Scanner;

public class JDBCTest08 {
    
    public static void main(String[] args) {
    
        // The user enters... On the console desc It's descending , Input asc It's ascending 
        Scanner s = new Scanner(System.in);
        System.out.println(" Please enter desc perhaps asc");
        String keyWords = s.nextLine();
        // perform SQL
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
    
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");

            stmt = conn.createStatement();

            String sql = "select ename from emp order by ename " + keyWords;
            rs = stmt.executeQuery(sql);
            // Traversal result set 
            while(rs.next()){
    
                System.out.println(rs.getString("ename"));
            }

        } catch (ClassNotFoundException e) {
    
            e.printStackTrace();
        } catch (SQLException throwables) {
    
            throwables.printStackTrace();
        } finally {
    
            if (rs != null) {
    
                try {
    
                    rs.close();
                } catch (SQLException throwables) {
    
                    throwables.printStackTrace();
                }
            }
            if (stmt != null) {
    
                try {
    
                    rs.close();
                } catch (SQLException throwables) {
    
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
    
                try {
    
                    rs.close();
                } catch (SQLException throwables) {
    
                    throwables.printStackTrace();
                }
            }
        }
    }
}

3、 ... and 、JDBC Transaction mechanism

JDBC Transaction mechanism :

1、JDBc Transactions in are automatically committed , What is auto submit ?

Just execute any one DML sentence , Automatically submit — Time . This is a JDBC Default transaction behavior . But in the actual business , Is usually N strip DML Statements can only be completed together , They must be guaranteed these DML Statements succeed or fail simultaneously in the same transaction .

file name :t_act.sql

purpose :bjpowernode;

source …

drop table if exists t_act;
create table t_act(
	actno int,
	balance double(7,2)// Be careful 7 Represents the number of significant digits ,2 Represents the number of decimal places .
);
insert into t_act(actno,balance) values(111,20000);
insert into t_act(actno,balance) values(222,0);
commit;
select * from t_act;
/* Focus on three lines of code : conn.setAutoCommit(false); conn.commit(); conn.rollback(); */
package ustc.java.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCTest10 {
    
    public static void main(String[] args) {
    
        Connection conn = null;
        PreparedStatement ps = null;
        try {
    
            //  Registration drive 
            Class.forName("com.mysql.jdbc.Driver");

            //  Get the connection 
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");

            //  Change auto commit to manual commit 
            conn.setAutoCommit(false);

            //  Get the precompiled database operation object 
            String sql = "update t_act set balance = ? where actno = ? ";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,10000);
            ps.setDouble(2,111);

            //  perform sql sentence 
            int count = ps.executeUpdate();

            /*String s = null; s.toString();*/

            ps.setInt(1,10000);
            ps.setDouble(2,222);
            count += ps.executeUpdate();

            System.out.println(count == 2 ? " Transfer succeeded " : " Transfer failure ");

            //  The program can be executed here , There is no exception , End of transaction , Manually submit data 
            conn.commit();
        } catch (Exception e) {
    
            //  Exception encountered , Roll back 
            if (conn != null) {
    
                try {
    
                    conn.rollback();
                } catch (SQLException throwables) {
    
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        }  finally {
    
            //  Release resources 
            if (ps != null) {
    
                try {
    
                    ps.close();
                } catch (SQLException throwables) {
    
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
    
                try {
    
                    conn.close();
                } catch (SQLException throwables) {
    
                    throwables.printStackTrace();
                }
            }
        }
    }
}

Four 、JDBC Encapsulation of tool class

img

jdbc.properti

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
user=root
password=123456
package com.bjpowernode.oa.utils;

import java.sql.*;
import java.util.ResourceBundle;

/** * JDBC Tool class of  */
public class DBUtil {
    

    //  Static variables : Execute... When the class is loaded .
    //  And it's sequential . Top down order .
    //  Attribute resource file binding 
    private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc");
    //  According to attribute profile key obtain value
    private static String driver = bundle.getString("driver");
    private static String url = bundle.getString("url");
    private static String user = bundle.getString("user");
    private static String password = bundle.getString("password");

    static {
    
        //  Registration drive ( You only need to register the driver once , In static code blocks .DBUtil When the class is loaded, execute .)
        try {
    
            // "com.mysql.jdbc.Driver"  It is the driver to connect to the database , Can't write dead . Because it may be connected in the future Oracle database .
            //  If connected oracle When it comes to databases , It needs to be revised java Code , It is a clear violation of OCP Opening and closing principle .
            // OCP Opening and closing principle : Open to expansion , Turn off for changes .( What is consistent with OCP Well ? During function expansion , It doesn't need to be modified java Source code .)
            //Class.forName("com.mysql.jdbc.Driver");

            Class.forName(driver);
        } catch (ClassNotFoundException e) {
    
            e.printStackTrace();
        }
    }

    /** *  Get database connection object  * @return conn  Connection object  * @throws SQLException */
    public static Connection getConnection() throws SQLException {
    
        //  Get the connection 
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    /** *  Release resources  * @param conn  Connection object  * @param ps  Database operation object  * @param rs  Result set object  */
    public static void close(Connection conn, Statement ps, ResultSet rs){
    
        if (rs != null) {
    
            try {
    
                rs.close();
            } catch (SQLException e) {
    
                e.printStackTrace();
            }
        }
        if (ps != null) {
    
            try {
    
                ps.close();
            } catch (SQLException e) {
    
                e.printStackTrace();
            }
        }
        if (conn != null) {
    
            try {
    
                conn.close();
            } catch (SQLException e) {
    
                e.printStackTrace();
            }
        }
    }

}

test DBUtil Tool classes and fuzzy queries

package ustc.java.jdbc;

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

/* 1、 test DBUtil Tool class  2、 Fuzzy query  */
public class JDBCTest {
    
    public static void main(String[] args) {
    
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
    
            conn =  DBUtil.getConnection();

            String sql = "select ename from emp where ename like ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,"_A%");

            rs = ps.executeQuery();

            while(rs.next()){
    
                System.out.println(rs.getString("ename"));
            }
        } catch (SQLException throwables) {
    
            e.printStackTrace();
        }finally{
    
            DBUtil.close(conn,ps,rs);
    }
}

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        conn =  DBUtil.getConnection();

        String sql = "select ename from emp where ename like ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1,"_A%");

        rs = ps.executeQuery();

        while(rs.next()){
            System.out.println(rs.getString("ename"));
        }
    } catch (SQLException throwables) {
        e.printStackTrace();
    }finally{
        DBUtil.close(conn,ps,rs);
}

}

 Conclusion 
 Recommend a simulated interview 、 Brush question artifact website 
 Click jump to enter the website [ Click to enter ](https://www.nowcoder.com/exam/oj?page=1&tab=%E8%AF%AD%E6%B3%95%E7%AF%87&topicId=220&fromPut=pc_csdncpt_jyjp_java)
1、 Algorithm (398 topic ): Interview must brush 100 topic 、 Introduction to algorithm 、 Interview frequency list 
2、SQL piece (82 topic ): Quick start 、SQL Will know 、SQL Advanced challenges 、 The real question of the interview 
3、 The real question of the written test of Dachang : Bytes to beat 、 Meituan 、 Baidu 、 tencent …
原网站

版权声明
本文为[Beijing and JIUPU]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260547338463.html