MySQL database - detailed explanation of the five JDBC objects (Java)

Table of contents

1. DriverManager: driver management object

1. Register driver: tell the program which database driver jar to use 

2. Get the database connection:

2. Connection: database connection object

1. Get the object to execute sql

2. Management affairs:

3. Statement: the object that executes sql

1、boolean execute(String sql) :

2、int executeUpdate(String sql) :

3、ResultSet executeQuery(String sql)  :

4. ResultSet: Result set object, encapsulating query results

boolean next():

getXxx(parameter): Get data

usage:              

5. PreparedStatement: object for executing sql

1. SQL injection problem:

2. Solve the sql injection problem:

3. Precompiled SQL:

4. Steps:


Let’s first look at the following code to understand the first four objects:

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

public class JDBCDemo {
    public static void main(String[] args) throws Exception{
        //注册驱动
//        Class.forName("com.mysql.jdbc.Driver");               //JDBC5之后可以不用注册驱动
        //获取数据库连接对象
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root");
        //定义sql语句
        String sql = "select * from db1.emp";
        //获取执行sql的对象Statement
        Statement stmt = conn.createStatement();
        //执行sql
        ResultSet resultSet = stmt.executeQuery(sql);
        //处理结果
        while(resultSet.next()) {                                     //让游标移动到下一行,true 表示有数据行,可以到下一行
            int id = resultSet.getInt(1);                    //获取id
            String name = resultSet.getString("ename");             //获取姓名
            System.out.println("id:" + id + " name:" + name);
        }
        //释放资源
        stmt.close();
        conn.close();
    }
}

1. DriverManager: driver management object

1. Register driver: tell the program which database driver jar to use 

static void registerDriver(Driver driver): Register with the given driver DriverManager. Write code using: Class.forName("com.mysql.jdbc.Driver");

By viewing the source code, we found that there is a static code block in the com.mysql.jdbc.Driver class.

static {
       try {
           java.sql.DriverManager.registerDriver(new Driver());
            } catch (SQLException E) {
                  throw new RuntimeException("Can't register driver!");
            }
}

So you can write it directly like this:

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

Note: The driver jar package after mysql5 can omit the step of registering the driver.

2. Get the database connection:

  1. 方法:static Connection getConnection(String url, String user, String password)  
  2. parameter:

         * url: Specify the path syntax of the connection
                   : jdbc:mysql://ip address (domain name): port number/database name
                   Example: jdbc:mysql://localhost:3306/db3
                   Details: If the connection is to the local mysql server, And the default port of mysql service is 3306, the url can be abbreviated as: jdbc:mysql:///database name
           * user: user name
           * password: password 

2. Connection: database connection object

1. Get the object to execute sql

                * Statement createStatement()

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root");
Statement stmt = conn.createStatement();

                * PreparedStatement prepareStatement(String sql)  

                        For usage details, see

                        5. PreparedStatement: object for executing sql

2. Management affairs:

  • Open the transaction: setAutoCommit(boolean autoCommit): Call this method to set the parameter to false, that is, open the transaction

                Start transaction before executing sql

  • Submit transaction: commit() 

                When all sql has been executed and the transaction is submitted

  • Rollback transaction: rollback() 

               Rollback transaction in catch

catch (Exception e) {
      try {
            if(conn != null)
                conn.rollback();          //若发生异常则回滚事务
           } 

3. Statement: the object that executes sql

1、boolean execute(String sql) :

Can execute arbitrary sql (understand) 

2、int executeUpdate(String sql) :

Execute DML (insert, update, delete) statements, DDL (create, alter, drop) statements

               * Return value: The number of affected rows. You can use the number of affected rows to determine whether the DML statement is successfully executed. If the return value is >0, the execution is successful. Otherwise, it fails, as shown in the following code segment:

Statement stmt = conn.createStatement();
int count = stmt.executeUpdate("update db1.account set balance = 1500 where id = 2");
if (count > 0)
    System.out.println("转账成功");
else
    System.out.println("转账失败");

3、ResultSet executeQuery(String sql)  :

Execute DQL (select) statement: see ResultSet object for usage

4. ResultSet: Result set object, encapsulating query results

  • boolean next():

The cursor moves down one row and determines whether the current row is at the end of the last row (whether there is data). If so, it returns false. If not, it returns true.

  • getXxx(parameter): Get data

            * Xxx: represents the data type, such as: int getInt(), String getString()
            * Parameters:
                1. int: represents the column number, starting from 1, such as: getString(1)
                2. String: represents the column name. For example: getDouble("balance")
            * Usage steps:
                1. Move the cursor down one line
                2. Determine whether there is data
                3. Get the data 

usage:              

//处理结果
ResultSet rs = stmt.executeQuery("update db1.account set balance = 1500 where id = 2");              
//循环判断游标是否是最后一行末尾。
while(rs.next()) {              //让游标移动到下一行,true 表示有数据行,可以到下一行
    int id = rs.getInt(1);                    //获取id
    String name = rs.getString("name");             //获取姓名
    double balance = rs.getDouble(3);              //获取工资
    System.out.println("id:" + id + " 姓名:" + name + " 工资:" + balance);
}

5. PreparedStatement: object for executing sql

1. SQL injection attack:

When splicing sql, there are some special keywords of sql that participate in string splicing. It will cause security problems, such as entering the user casually, entering the password: a' or 'a' = 'a ( universal password ), such as:
           sql: select * from user where username = 'fhdsjkf' and password = 'a' or ' a' = 'a' 

The database does not use such a username and password, but it can be queried normally.

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = in.nextLine();
        System.out.println("请输入密码:");
        String password = in.nextLine();
        boolean flag = new Sign().login2(username,password);
        if(flag)
            System.out.println("登录成功!");
        else
            System.out.println("用户名或密码错误!");
    }
public boolean login(String username ,String password){
        if(username == null || password == null){
            return false;
        }
        //连接数据库判断是否登录成功
        Connection conn = null;
        Statement stmt =  null;
        ResultSet rs = null;
        //1.获取连接
        try {
            conn =  JDBCUtils.getConnection();
            //2.定义sql
            String sql = "select * from db1.user where username = '"+username+"' and password = '"+password+"' ";
            System.out.println(sql);
            //3.获取执行sql的对象
            stmt = conn.createStatement();
            //4.执行查询
            rs = stmt.executeQuery(sql);
            return rs.next();//如果有下一行,则返回true

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,stmt,conn);
        }
        return false;
    }

 2. Solve the sql injection problem:

Use PreparedStatement object to solve

3. Precompiled SQL:

Parameters use ? as placeholder

4. Steps:

1. Import the driver jar package mysql-connector-java-5.1.37-bin.jar
2. Register the driver
3. Get the database connection object Connection
4. Define sql
                * Note: What parameters are used for sql? as a placeholder. For example: select * from user where username = ? and password = ?;
5. Get the object to execute the sql statement PreparedStatement Connection.prepareStatement(String sql) 
6. Give? Assignment:
                * Method: setXxx(parameter 1, parameter 2)
                    * Parameter 1:? The position number starts from 1
                    * Parameter 2:? The value of
7. Execute sql, accept the returned results, no need to pass sql statements
8. Process the results
9. Release resources

5. Usage:

Modify login method:

public boolean login(String username,String password) {
        if (username == null || password == null)
            return false;
        Connection conn = null;
        PreparedStatement pstmt = null;                //防止sql注入问题
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();         //用自己写的JDBCUtils连接数据库
            String sql = "select * from db1.user where username = ? and password = ?";
            pstmt = conn.prepareStatement(sql);                            //获取sql的对象
            pstmt.setString(1,username);          //给?赋值
            pstmt.setString(2,password);
            rs = pstmt.executeQuery();                          //执行查询
            return rs.next();                          //如果有下一行则返回true
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,pstmt,conn);               //用自己写的JDBCUtils释放资源
        }
        return false;
}

Note: PreparedStatement will be used later to complete all operations of addition, deletion, modification and query
            1. It can prevent SQL injection
            2. It is more efficient

Guess you like

Origin blog.csdn.net/weixin_51418964/article/details/122956912