[Advanced Java] In-depth understanding of JDBC: Detailed explanation of Java database connection

Insert image description here

Databases are one of the core components of modern applications. Whether it's a web application, a mobile application, or a desktop application, almost all applications need to interact with a database to store and retrieve data. Java provides a powerful way to interact with databases, JDBC (Java Database Connectivity). This article will delve into every aspect of JDBC, from basic concepts to practical programming examples to help you understand and use JDBC.

What is JDBC?

JDBC is the abbreviation of Java Database Connectivity, which is Java's standard API for interacting with relational databases. JDBC allows Java applications to connect to different database management systems (such as MySQL, Oracle, PostgreSQL, etc.), perform SQL queries and updates, and process result sets.

With JDBC, you can accomplish the following tasks:

  • Connect to database
  • Send SQL query
  • Process query results
  • Update database data
  • Manage database connections

JDBC architecture

Before we delve into how to use JDBC, let's take a look at the architecture of JDBC. The JDBC architecture is divided into two main parts: JDBC API and JDBC driver.

JDBC API

The JDBC API is a set of interfaces and classes provided by Java for connecting to a database and performing database operations. These interfaces and classes are located in java.sqlthe and javax.sqlpackages.

The following are some core interfaces and classes of the JDBC API:

  • DriverManager: Class used to manage database drivers and responsible for establishing database connections.
  • Connection: Represents the connection to the database and is used to create Statementobjects.
  • Statement: Object used to execute SQL queries.
  • PreparedStatement: Inherited from Statement, used to execute precompiled SQL queries, improving performance and security.
  • CallableStatement: Inherited from PreparedStatement, used to execute database stored procedures.
  • ResultSet: Represents the result set of SQL query and is used to retrieve query results.

JDBC driver

The JDBC driver is a concrete class library provided by the database vendor that implements the JDBC API. Each database vendor needs to provide its own JDBC driver so that Java applications can communicate with its database.

There are four types of JDBC drivers:

  1. Type 1 driver (JDBC-ODBC bridge driver) : This driver uses ODBC (Open Database Connectivity) to connect to the database through a Java application. This type is not recommended because it relies on the local operating system's ODBC driver.

  2. Type 2 driver (native API driver) : This driver uses the database vendor's native library to connect to the database. It requires a separate driver on each platform.

  3. Type 3 driver (network protocol driver) : This driver uses a middle-tier server to forward JDBC requests and then communicate with the database. This driver is usually implemented in pure Java and does not require a specific database driver to be installed on the client.

  4. Type 4 driver (pure Java driver) : This driver is written entirely in Java and does not need to rely on native libraries. It is the most commonly used JDBC driver type.

Connect to database using JDBC

Below we will use a simple example to demonstrate how to use JDBC to connect to the database, execute SQL queries and process the query results.

Step 1: Load the database driver

First, you need to load the database driver you want to use. For different databases, the class name of the driver is also different. Here are some common database driver class names:

  • MySQL driver:com.mysql.cj.jdbc
try {
    
    
    // 加载 MySQL 驱动程序
    Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
    
    
    System.err.println("无法加载数据库驱动程序");
    e.printStackTrace();
}

In the above code, we use Class.forName()the method to load the MySQL driver. If loading fails, ClassNotFoundExceptionan exception will be thrown.

Step 2: Establish a database connection

Once the driver loads successfully, we can establish the connection to the database. In this step, you need to provide the URL of the database, username and password.

String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";

try {
    
    
    // 建立数据库连接
    Connection connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
    
    
    System.err.println("无法建立数据库连接");
    e.printStackTrace();
}

In the above code, we use DriverManager.getConnection()the method to establish the connection to the database. This method accepts three parameters: the database URL, username, and password. If the connection fails, SQLExceptionan exception will be thrown.

Step 3: Execute SQL query

Once the database connection is established, we can execute SQL queries. Below is a simple example that demonstrates how to execute a query and get the results.

try {
    
    
    // 创建 Statement 对象
    Statement statement = connection.createStatement();
    
    // 执行 SQL 查询
    String sql = "SELECT * FROM employees";
    ResultSet resultSet = statement.executeQuery(sql);
    
    // 处理查询结果
    while (resultSet.next()) {
    
    
        int employeeId = resultSet.getInt("employee_id");
        String firstName = resultSet.getString("first_name");
        String lastName = resultSet.getString("last_name");
        
        System.out.println("Employee ID: " + employeeId);
        System.out.println("First Name: " + firstName);
        System.out.println("Last Name: " + lastName);
    }
    
    // 关闭结果集和语句
    resultSet.close();
    statement.close();
} catch (SQLException e) {
    
    
    System.err.println("SQL 查询失败");
    e.printStackTrace();
}

In the above code, we first create an Statementobject and then use executeQuery()the method to execute the SQL query. Query results are stored in ResultSetobjects, and we can use resultSet.next()the methods to iterate over the rows in the result set and retrieve the data using column names or indexes.

Step 4: Close the connection

Finally, after you have finished using the database connection, be sure to close it to release resources.

try {
    
    
    // 关闭数据库连接
    connection.close();
} catch (SQLException e) {
    
    
    System.err.println("关闭数据库连接失败");
    e.printStackTrace();
}

This is a simple JDBC query example. Of course, JDBC also supports more complex query, update and transaction processing functions.

Summarize

JDBC is Java's standard API for interacting with databases, allowing you to connect to different database management systems, perform SQL queries and update data. This article introduces the basic concepts and usage of JDBC, including loading drivers, establishing connections, executing queries, and closing connections. I hope this article helps you better understand and use JDBC to build powerful database applications.

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/133444235