Introduction to JDBC native connection and connection pool

1. Steps


  1. Class.forName() loads the database connection driver.


    The first: directly register the database driver DriverManager.registerDriver(new Driver());
    The second: use the reflection mechanism to load the database driver indirectly, Class.forName("com.mysql.jdbc.Driver"); (commonly used)

  2. The class DriverManager responsible for managing the JDBC driver will identify the loaded driver, and DriverManager.getConnection() gets the data connection object;

  3. There are 2 ways to get an instance of the Connection object, Statement, PreparedStatement
  4. The returned results are handled with the ResultSet class.
  5. When an exception occurs when closing the result set, closing the session, or closing the connection, the transaction is rolled back.

example

public class Test {
    public static void main(String[] args) throws Exception {
        //注册驱动,反射方式加载
        Class.forName("com.mysql.jdbc.Driver");
        //设置url
        String url = "jdbc:mysql://127.0.0.1:3306/day08";//person是数据库名,连接是数据库须要开启
        //设置用户名
        String username = "root";
        //设置密码
        String password = "root";
        //获得连接对象
        Connection con = DriverManager.getConnection(url, username, password);
        //System.out.println(con);
        //获得执行者对象
        String sql = "select * from phones";
        PreparedStatement ps = con.prepareStatement(sql);
        //获得结果集
        ResultSet rs = ps.executeQuery();
        //结果集处理,
        while(rs.next()){
            System.out.println(rs.getString("id")+"  "+rs.getString("pinpai")+"  "+rs.getString("xinghao")+"  "+rs.getString("jiage"));
        }
        //释放资源
        rs.close();
        ps.close();
        con.close();
    }
}

2. The difference and pros and cons of CreateStatement(Statement) and PrepareStatement.

  • Use the CreateStatement method to create the stmt object, and then pass some of the statement fragments of his query.
String sql = "select * from users where  username= '"+username+"' and userpwd='"+userpwd+"'";  
stmt = conn.createStatement();  
rs = stmt.executeQuery(sql);
  • Use the PrepareStatement method to create a pstmt object, and then query a part of the statement fragment through this object.
String sql = "select * from users where  username=? and userpwd=?";  
pstmt = conn.prepareStatement(sql);  
pstmt.setString(1, username);  
pstmt.setString(2, userpwd);  
rs = pstmt.executeQuery(); 
  • The main difference between PrepareStatement and Statement is that the variables in the SQL statement are extracted. PrepareStatement improves code readability.
  • PreparedStatement variables can be represented by placeholders, which can prevent SQL injection
  • PreparedStatement interface inherits Statement, PreparedStatement instance contains compiled SQL statement, so its execution speed is faster than Statement object.
  • As a subclass of Statement, PreparedStatement inherits all the functionality of Statement. The three methods execute, executeQuery and executeUpdate have been changed so that they no longer require parameters

  • In JDBC applications, never use Statement:

    1. Code readability and maintainability.Statement needs to be spliced ​​continuously, and PreparedStatement does not.
    2. PreparedStatement maximizes performance. DB has caching mechanism, the same prepared statement is called again without needing to compile again.
    3. The most important point is to greatly improve the security. Statement is easy to be injected by SQL, and the content passed in PreparedStatementc will not have any matching relationship with the SQL statement

3. Connection pool

  • What is the mechanism of connection pooling in relational databases? - - Establish a buffer pool for database connections.
    1. Get or create an available connection from the connection pool
    2. After use, return the connection to the connection pool
    3. Disconnects all connections and releases system resources occupied by connections before the system shuts down
    4. Ability to handle invalid connections and limit the total number of connections in the connection pool to not be lower or higher than a certain limit.

Concept:
* The minimum number of connections is the data connection that the connection pool keeps. If the program does not use much database connection, a lot of database connection resources will be wasted.
* The maximum number of connections is the maximum number of connections that the connection pool can apply for. If data connection requests exceed this number, subsequent data connection requests will be added to the waiting queue, which will affect subsequent database operations.
* If the difference between the minimum number of connections and the maximum number of connections is too large, the first connection request will profit, and the subsequent connection requests
exceeding to establishing a new database connection. However, these database connections that are larger than the minimum number of connections will not be released immediately after they are used up, they will be placed in the connection
pool to wait for reuse or to be released after idle timeout.
* It can be understood like this: the number of connections in the database pool has always been maintained at a number not less than the minimum number of connections. When the number is not enough, the database will create some connections until a maximum number of connections, and then the connection to the database will wait.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324834202&siteId=291194637