Detailed explanation of JDBC and API, Druid connection pool

JDBC concept

JDBC is a set of APIs that use the Java language to operate relational databases Full name: Java DataBase Connectivity

JDBC essence

  • A set of rules defined by the official (sun company) to operate all relational databases, that is, the interface
  • Various database vendors implement this set of interfaces and provide database driver jar packages
  • We can use this set of interfaces (JDBC) to program, and the code that is actually executed is the implementation class in the driver jar package

JDBC benefits

  • All database vendors use the same interface, and Java code does not need to be developed separately for different databases
  • The underlying database can be replaced at any time, and the Java code for accessing the database remains basically unchanged

Connection steps (My MySQL 8.0 is somewhat different from 5, remember to import the package)

        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接
        String url = "jdbc:mysql://localhost:3306/database?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
        String user = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, user, password);
        //3.定义sql
        String sql = "";
        //4.获取执行sql的对象
        Statement stmt = conn.createStatement();
        //5.执行sql
        int count = stmt.executeUpdate(sql);//受影响的行数
        //6.关闭资源
        stmt.close();
        conn.close();

 JDBC-API Detailed Explanation

  • DriverManager

The driver management class has two functions - registering the driver and obtaining the database connection

//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//查看Driver源码,发现静态代码块,上面那句代码执行时,这个静态代码块里的内容会执行
static {
        try {
            //调用DriverManager的注册方法
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }

hint:

        The driver package after MySQL 5 can omit the step of registering the driver

        Automatically load the driver class in the META-INF/services/java.sql.Driver file in the jar package

        //2.获取连接
        String url = "jdbc:mysql://localhost:3306/database1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
        String user = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, user, password);
  • Connection

Role: Get the object that executes SQL; manage transactions

1. Get the object to execute SQL

Common execution SQL object
Statement createStatement()
Precompiled $QL execution SQL object: preventing SQL injection
PreparedStatement prepareStatement (sql)
Executing stored procedure object
CallableStatement prepareCall (sql)

2. Transaction management

MySQL transaction management
        start transaction : BElGIN; /START TRANSACTION;

        Commit transaction : COMMIT;
        rollback transaction : ROLLBACK;
        MySQL automatically commits transaction by default

JDBC transaction management: Three corresponding methods are defined in the Connection interface
        to start a transaction: setAutoCommit(boolean autoCommit): true is to automatically commit the transaction; false is to manually commit the transaction, that is, to start the transaction

        Commit transaction: commit()
        Rollback transaction: rollback()

try {
//开启事务
conn .setAutocommit(false);

//5.执行sql
int count1 = stmt.executeUpdate(sql1);//受影响的行数
//6.处理结果
system.out.println(count1);

//5.执行sql
int count2 = stmt.executeUpdate(sql2);//受影响的行数
//6.处理结果
system.out.println(count2);

//提交事务
conn.commit();
}catch (Exception throwables) {
//回滚事务
conn.rollback();
throwables.printStackTrace(;
}
  • Statement

statement is used to execute sql statement.

executeUpdate(sql): Execute DML (addition, deletion and modification of data), DDL statement

Return value (int type):

        (1) The number of rows affected by the DML statement

        (2) After the DDL statement is executed, it may return 0 if the execution is successful

executeQuery(sql): execute DQL statement

Return value (ResultSet): ResultSet result set object

  • ResultSet

result set object

1. Encapsulate the query result of the DQL statement

boolean next():

(1) Move the cursor down one line from the current position from the header

(2) Determine whether the current row is a valid row return value:

true: valid row, the current row has data false: invalid row, the current row has no data

//配合使用
while(rs.next()){
    int a=rs.getInt(1);
    ...
    ...
    ...
    ...
}

xxx getXxx(parameter):

Get data
xXx: data type; such as: int getInt(parameter) ; String getString(parameter)

Parameters: int: column number, starting from 1 String: column name
 

  • PreparedStatement

An interface, inherited from statement.

effect:

        1. Precompile and execute SQL statements: prevent SQL injection problems (SQL injection is a method of modifying pre-defined SQL statements by operating input to achieve code execution to attack the server)

//获取PreparedStatement 对象
//SQL语句中的参数值,使用?占位符替代
String sql = "select * from user where username = ? and password = ?";
//通过Connection对象获取,并传入对应的sql语句
PreparedStatement pstmt = conn.prepareStatement(sql);
//设置参数值
PreparedStatement对象:setXxx(参数1,参数2)//给﹖赋值>Xxx:数据类型;如setInt (参数1,参数2)
//参数:
//参数1:?的位置编号,从1开始      参数2:?的值
③执行SQL
executeUpdate(); // executeQuery();:不需要再传递sql

The precompilation function of PreparedStatement is closed, and the parameter after the url is added: useServerPrepStmts=true
The rest is messy and directly puts the screenshot

 database connection pool

Introduction

  • The database connection pool is a container responsible for allocating and managing database connections (Connection)
  • It allows an application to reuse an existing database connection instead of re-establishing a new one;
  • Release database connections whose idle time exceeds the maximum idle time to avoid missing database connections caused by not releasing database connections

        Benefits: resource reuse; improve system response speed; avoid database connection failure

accomplish

        Standard interface: DataSource

        The standard interface of the database connection pool provided by the official (SUN), which is implemented by a third-party organization.

        Common database connection pools: DBCP, C3P0, Druid

        Each database connection pool will provide a getConnection() method inherited from DataSource

connection steps

        1. Import the jar package druid-1.1.12.jar

        Download address: Central Repository: com/alibaba/druid/1.2.9

        the latest i downloaded

        2. Define the configuration file

        3. load configuration file

        4. Get the database connection pool object

        5. get connection

        //3.加载配置文件
        Properties prop=new Properties();
        prop.load(new FileInputStream("druid.properties"));
        //4.获取连接池对象
        DataSource ds= DruidDataSourceFactory.createDataSource(prop);
        //5.获取数据库连接
        Connection conn=ds.getConnection();

Guess you like

Origin blog.csdn.net/m0_48385518/article/details/124420055