What is JDBC? this article tells you

        The full name of JDBC is Java Database Connect (Java Database connect), which is a set of Java API for executing SQL statements. It is a bridge between Java and the database. It is a specification rather than an implementation. It can query, update and delete data in the database by executing SQL statements.

        

        The way the application uses JDBC to access the database is shown in the following figure:

        As can be seen from the figure above, when an application uses JDBC to access a specific database, it needs to connect with different database drivers. Since the database drivers provided by different database vendors are different, in order to enable the application program to truly establish a connection with the database, JDBC not only needs to provide an API for accessing the database, but also needs to encapsulate the details of communication with various database servers, and the databases of different vendors have corresponding realization.

        The following figure describes the specific implementation details of JDBC, as shown in the figure below:

As can be seen from the figure above, the implementation of JDBC consists of three parts.

        (1) JDBC driver manager: responsible for registering a specific JDBC driver, mainly through the java.sql.DriverManager class;

        (2) JDBC driver API: developed by Sun, the most important interface is java.sql.Driver interface;

        (3) JDBC driver: It is a database driver created by the database manufacturer, also known as the JDBC driver, which is responsible for connecting to a specific database and handling communication details.

        

JDBC programming steps 

        Databases from various manufacturers have corresponding implementations, and the codes in this article are all implemented for MySQL databases.

1. Register the driver

        Before writing code, you need to install the MySQL third-party library. The mysql-connector-java-8.0.29-bin.jar package can be downloaded from the Internet or found in the MySQL installation directory.

    try {
        Driver driver = new com.mysql.cj.jdbc.Driver();
        DriverManager.registerDriver(driver);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

        Following is the source code of com.mysql.cj.jdbc.Driver class

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

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

        The driver can also be loaded through the Class.forName method. This method loads this class into the JVM. When loading, the static initialization block will be executed to complete the related work of driver initialization. 

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

2. Establish a connection

    String url = "jdbc:mysql://localhost:3306/jdbc"; // 数据库URL
    String user = "root"; // 数据库用户名
    String password = "123456"; // 数据库密码
    Connection conn = null;
    try {
        conn= = DriverManager.getConnection(url, user, password);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

3. Get the database operation object (precompiled object)

        Get the database operation object to implement the database insert operation

public class JDBC {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/jdbc"; //定义数据库的
        String user = "root";
        String password = "123456";
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);

            stmt = conn.createStatement();
            String sql= "insert into user(id, name, gender, age) values(2, '张三', '男', 18)"; 
            
            stmt.executeUpdate(sql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

       Obtain the database operation object to implement the database update operation

public class JDBC {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/jdbc"; //定义数据库的
        String user = "root";
        String password = "123456";
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);

            stmt = conn.createStatement();
            String sql = "update user set name = '张三' where age = 20"; // 修改SQL语句
            
            stmt.executeUpdate(sql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

        Get the database operation object and implement the database delete operation

public class JDBC {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/jdbc"; //定义数据库的
        String user = "root";
        String password = "123456";
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);

            stmt = conn.createStatement();
            String sql = "delete from user where name = '张三'"; // 删除SQL语句
            
            stmt.executeUpdate(sql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

        Obtain database precompiled objects to implement database insertion operations

public class JDBC {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/jdbc"; //定义数据库的
        String user = "root";
        String password = "123456";
        Connection conn = null;
        PreparedStatement pre = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);
            String sql = "insert into user(id, name, gender, age) values (?, ?, ?, ?)";

            pre = conn.prepareStatement(sql);
            pre.setInt(1,1);
            pre.setString(2,"张三");
            pre.setString(3,"男");
            pre.setInt(4,18);

            pre.executeUpdate();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

4. Processing query result set

        Get the database operation object, realize the database query operation, and print the result set

public class JDBC {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/jdbc"; //定义数据库的
        String user = "root";
        String password = "123456";
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);

            stmt = conn.createStatement();
            String select = "select * from user where name = '张三'";
            rs = stmt.executeQuery(select);
            while (rs.next()) {
                System.out.println(rs.getString("id") + "," + rs.getString("name")
                + "," + rs.getString("gender") + "," + rs.getString("age"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

        Obtain database precompiled objects, implement database query operations, and print result sets

public class JDBC {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/jdbc"; //定义数据库的
        String user = "root";
        String password = "123456";
        Connection conn = null;
        PreparedStatement pre = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);
            String sql = "select * from user where name = ?";

            pre = conn.prepareStatement(sql);
            pre.setString(1,"藏三");

            rs = pre.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString("id") + "," + rs.getString("name")
                + "," + rs.getString("gender") + "," + rs.getString("age"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

5. Release resources

    try {
        if (rs != null) {
            rs.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    try {
        if (statement != null) {
            statement.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    try {
        if (conn != null) {
            conn.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

        

The similarities and differences, advantages and disadvantages of Statement and PreparedStatement


The same point: both are used to execute SQL statements

The difference: PreparedStatement needs to be created according to the SQL statement. It can specify the corresponding value by setting parameters, instead of using string splicing like Statement.

Advantages of PreparedStatements

        1. It uses parameter settings with good readability and is not easy to remember wrongly. Using string concatenation in the statement is less readable and maintainable.

        2. It has a pre-compilation mechanism, and its performance is faster than statement.

        3. It can effectively prevent SQL injection attacks.

The difference between execute and executeUpdate


The same point: Both can perform operations such as adding, deleting, and modifying.

Differences: 1. execute can execute the query statement, and then get the result through getResult. executeUpdate cannot execute the query statement; 2. execute returns Boolean type, true means that the query statement is executed, and false means that the insert, delete, update, etc. are executed. The return value of executeUpdate is int, indicating how many pieces of data have been affected.

        

This is the end of the basic introduction to JDBC. Welcome to discuss in the comment area.

Guess you like

Origin blog.csdn.net/qq_43500084/article/details/127678124