当前位置:网站首页>Introduction to JDBC (I) DML operation

Introduction to JDBC (I) DML operation

2022-06-23 05:23:00 The silent Lord returns to the sand

  1. JDBC operation ( a key )
    Review previous ways of connecting to the database
    DOS Command mode , Graphically
    shortcoming :
    It can only be simply SQL Statement testing , Cannot manipulate database in project

    Export through java Connect to the database in code mode —JDBC
    summary :JDBC Is a set of standards for connecting to databases ; The specific implementation is provided by different databases

    JDBC The core idea :
     Insert picture description here

    JDBC Operation steps :
     Insert picture description here

     Specific application :
    

    install 5.7 The database of , Driver package selection 5.X Driver package
    Import driver package :

    • Create a new one under the project lib Folder , To hold jar file .
  • take mysql drive mysql-connector-java-5.1.X Copy to project's lib In the folder .
  • Choose lib Folder right-click Add as Libraay, Click on OK.

Common abnormal problems :
ClassNotFoundException Driver load failed
MySQLSyntaxErrorException: A database or SQL Statement exception
SQLException: Access denied Account or password error
MySQLIntegrityConstraintViolationException Primary key conflict

4.1 DML operation

// Case study : Add a piece of data to the position table 
public class DMLTest {
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
        //1. The load driver 
        Class.forName("com.mysql.jdbc.Driver");
        //2. Get the connection object through the driver manager  alt+enter Pop up exceptions and assignment variables 
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1", "root", "123");
        //3. Get the execution object through the connection object 
        Statement st = conn.createStatement();
        //4. Add, delete, modify and check   Additions and deletions :executeUpdate
        //String sql = "insert into t_jobs(job_id,job_title,min_salary,max_salary) values('QF_PRA','PRA',13000,18000)";
        //String sql = "update t_jobs set min_salary=20000,max_salary=30000 where job_id='QF_PRA'";
        String sql = "delete from t_jobs where job_id='QF_PRA'";
        //5. Feedback results 
        int result = st.executeUpdate(sql);
        System.out.println(" The number of items affected :"+result);

        //6. close resource , Turn down the small one first and then turn it up 
        DBUtils.closeAll(st,conn);
    }
}

4.2 DQL operation

class  Student{
    
    private  int id;
    private  String name;
    private  int  age;
	
     //set/get And construction method 
}

// Query the data of the student table 
public class DQLTest {
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "123");
        Statement st = conn.createStatement();
        // Get the result set 
        ResultSet rs = st.executeQuery("select * from student");
        List<Student> list = new ArrayList<>();
        // Loop traversal , Get all the records ( Each cycle , Is a record 
        while(rs.next()){
    
            //int id = rs.getInt(1); //1 On behalf of the 1 Column ; Application scenarios : Aggregate query feedback 
            int id = rs.getInt("id");  //id: The field name gets the value 
            String name = rs.getString("name");
            int age = rs.getInt("age");
            System.out.println(id+"-->"+name+"-->"+age);
            // Application scenarios : Feedback on scattered content , Object encapsulation should be required ,
                    list.add(new Student(id,name,age));
        }

        System.out.println(" Data stored in the collection :"+list);
        DBUtils.closeAll(rs,st,conn);  // close resource 
    }
}

4.3 Secure login cases

  • Create a user table User
    • id , Primary key 、 Automatic growth .
    • user name , String type , only 、 Non empty
    • password , String type , Non empty
    • Phone number , String type
  • Insert 2 Test statements

To realize the login

  • Enter the user name and password through the console user .
  • The user name and password entered by the user are the conditions , Write a query SQL sentence .
  • If the user exists , Prompt for successful login , Otherwise, the prompt fails .
public class LoginTest {
    
    public static void main(String[] args) {
    
        System.out.println(" Please enter a user name ");
        Scanner sc = new Scanner(System.in);
        String username = sc.nextLine();  // Get a line of content 
        System.out.println(" Please input a password ");
        String password = sc.nextLine();
        if(login2(username,password)){
      // Login function 
            System.out.println(" Login successful ~!");
        }else{
    
            System.out.println(" Login failed ~!");
        }
    }

    private static boolean login2(String username, String password) {
    
        Connection conn = null;
        PreparedStatement prst   = null;
        ResultSet rs    = null;
        try {
    
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "123");
            //PreparedStatement: Preprocess the execution object  ? As a placeholder 
            // benefits : 1. High safety , It's solved sql Injection problem 
                  //2.  The execution performance will be higher 
                  //3.  Convenient for batch processing 
            prst = conn.prepareStatement("select count(*) from user where username=? and password=?");
            // Parameters 1: Corresponds to the first placeholder ?  Subscript from 1 Start 
            prst.setString(1,username);
            prst.setString(2,password);
            // Get the result set 
            //sql Injection potential 
            rs = prst.executeQuery();
            if(rs.next()){
    
                int result = rs.getInt(1); // The aggregate function has only one field 
                return result>0;  //result Not less than 0, Then return to true
            }

        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            DBUtils.closeAll(rs,prst,conn);
        }
        return false;
    }

    private static boolean login(String username, String password) {
    
        Connection conn = null;
        Statement st    = null;
        ResultSet rs    = null;
        try {
    
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "123");
            st = conn.createStatement();
            // Get the result set 
            //sql Injection potential 
            String sql = "select count(*) from user where username='"+username+"' and password='"+password+"'";
            rs = st.executeQuery(sql);
            if(rs.next()){
    
                int result = rs.getInt(1); // The aggregate function has only one field 
                return result>0;  //result Not less than 0, Then return to true
            }

        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            DBUtils.closeAll(rs,st,conn);
        }
        return false;
    }
}

原网站

版权声明
本文为[The silent Lord returns to the sand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230309305677.html