[Java Advanced] Detailed explanation of JDBC DriverManager

Insert image description here

JDBC (Java Database Connectivity) is an API in the Java standard library for interacting with databases. It allows Java applications to connect to a variety of different database management systems (DBMS), perform SQL queries and update operations, and handle database transactions. In JDBC, DriverManagerit is a key class used to manage database drivers and establish database connections. This article will introduce DriverManagerthe usage of JDBC in detail, for basic beginners, and help you quickly get started with JDBC database connection.

What is DriverManager?

DriverManagerIs part of the Java JDBC API and is a class used to manage database drivers. Its main functions include:

  1. Register a database driver: Before you can use JDBC to connect to a database, you must first register the driver for your database. DriverManagerResponsible for loading and registering these drivers.

  2. Create database connection: DriverManagerAllows you to create a connection to the database, which is the first step in performing SQL operations.

  3. Manage database connection pools: A connection pool is a set of pre-created database connections that can be reused when needed to improve performance. DriverManagerCan be used with connection pooling.

Register database driver

Before you start using JDBC to connect to a database, you need to register the driver for your database. Different database vendors provide different JDBC drivers, so you need to download and register the corresponding driver according to the type of database used.

Typically, the database driver is a JAR file that you need to add to your project's classpath. Then, in your Java code, Class.forName()register the driver through the method. For example:

import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCDemo {
    
    
    public static void main(String[] args) {
    
    
        // 注册 MySQL 驱动程序
        try {
    
    
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we registered the driver for the MySQL database. Make sure to replace with the driver class name of the database you are using.

Create database connection

Once the database driver is registered, you can use DriverManagerto create a connection to the database. Connections are key to performing SQL operations.

The following is an example of creating a database connection:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCDemo {
    
    
    public static void main(String[] args) {
    
    
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";

        try {
    
    
            // 创建数据库连接
            Connection connection = DriverManager.getConnection(url, username, password);
            
            // 在此处执行数据库操作
            
            // 关闭连接
            connection.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we DriverManager.getConnection()create a connection to the MySQL database using the method. You need to provide the connection URL, username and password as parameters. The format of the connection URL is usually jdbc:数据库类型://主机名:端口号/数据库名.

Manage database connection pool

In practical applications, connection pools are often used to manage database connections to reduce connection creation and destruction overhead and improve application performance and response speed. Although DriverManagercan be used to create connections, it does not directly support connection pooling functionality. Typically, you would use a third-party connection pooling library such as Apache Commons DBCP, C3P0, or HikariCP.

The following is an example using HikariCP connection pooling:

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class JDBCDemo {
    
    
    public static void main(String[] args) {
    
    
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/mydatabase");
        config.setUsername("root");
        config.setPassword("password");

        // 创建 Hikari 数据源
        HikariDataSource dataSource = new HikariDataSource(config);

        try {
    
    
            // 从连接池获取连接
            Connection connection = dataSource.getConnection();
            
            // 在此处执行数据库操作
            
            // 关闭连接
            connection.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

Configure HikariCP connection pool

In the above example, we used HikariCP connection pool. To configure a connection pool, you create an HikariConfigobject, set the parameters for the connection pool, and then use this configuration object to create HikariDataSourcea data source.

Here are some common connection pool configuration parameters:

  • jdbcUrl: JDBC connection URL of the database.
  • usernameand password: database username and password.
  • minimumIdle: The minimum number of idle connections maintained in the connection pool.
  • maximumPoolSize: The maximum number of connections maintained in the connection pool.
  • connectionTimeout: Get the connection timeout.
  • idleTimeout: Timeout period for idle connections.
  • maxLifetime: The maximum lifetime of the connection.

You can configure these parameters based on your application requirements and database performance tuning needs.

Get a connection using a connection pool

Once a connection pool is configured, you can use HikariDataSourcethe object to obtain a database connection without explicitly creating or closing the connection. The connection pool is responsible for managing the creation, destruction and reuse of connections.

// 从连接池获取连接
Connection connection = dataSource.getConnection();

This way you can reuse connections within your application without having to worry about the overhead of connection creation and destruction.

close connection

Whether DriverManagera connection is created using or obtained from a connection pool, it should be closed after use to release resources and avoid resource leaks.

// 关闭连接
connection.close();

Exception handling

When writing JDBC code, you should handle exceptions that may occur. Common exceptions include SQLException(database access exception), ClassNotFoundException(driver not found exception), etc. Proper exception handling can make your application more robust.

Summarize

This article details DriverManagerthe usage of JDBC, including registering a database driver, creating a database connection, and using a connection pool to manage connections. JDBC is a key part of interacting with databases, and mastery of it is essential for developing Java database applications. I hope this article will be helpful to you and make it easier for you to use JDBC to connect and operate the database. If you have any questions or need further assistance, please feel free to ask me.

Author information

Author: Fanyi
CSDN: https://techfanyi.blog.csdn.net
Nuggets: https://juejin.cn/user/4154386571867191

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/133467419