7.2. Database connection and operation

1. Use database connection pool

Database connection pooling can improve application performance because establishing a database connection is a time-consuming operation. Many open source and commercial connection pool implementations are available, such as HikariCP, Apache DBCP, and C3P0. Here is a simple example showing how to use HikariCP connection pool:

First, add HikariCP dependency to the project:

Maven:

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>4.0.3</version>
</dependency>

Gradle:

implementation 'com.zaxxer:HikariCP:4.0.3'

Next, configure and use the HikariCP connection pool:

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

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

public class JdbcConnectionPoolExample {
    private static HikariDataSource dataSource;

    static {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true");
        config.setUsername("root");
        config.setPassword("mypassword");
        config.setMaximumPoolSize(10);
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource = new HikariDataSource(config);
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void main(String[] args) {
        try (Connection connection = getConnection()) {
            System.out.println("Connected to database!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

2. Execute batch processing

Batch processing can combine multiple SQL statements into a batch and send it to the database server for execution at one time. This reduces network round trips and improves performance. Here is a simple example showing how to insert data using batch processing:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class JdbcBatchProcessingExample {
    public static void main(String[] args) {
        try {
            // 加载数据库驱动并连接到数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            // 使用PreparedStatement创建批处理
            String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 添加批处理参数
            preparedStatement.setString(1, "User 1");
            preparedStatement.setInt(2, 20);
            preparedStatement.addBatch();

            preparedStatement.setString(1, "User 2");
            preparedStatement.setInt(2, 25);
            preparedStatement.addBatch();

            preparedStatement.setString(1, "User 3");
            preparedStatement.setInt(2, 30);
            preparedStatement.addBatch();

            // 执行批处理
            int[] rowsAffected = preparedStatement.executeBatch();
            System.out.println("Rows affected: " + Arrays.toString(rowsAffected));

            // 关闭资源
            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Get database metadata

Database metadata provides detailed information about the database, such as supported SQL features, database version, and table structure. It can be obtained through the method Connectionof the object getMetaData(). Here is a simple example showing how to get database metadata:

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class JdbcDatabaseMetaDataExample {
    public static void main(String[] args) {
        try {
            // 加载数据库驱动并连接到数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url= "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            // 获取数据库元数据
            DatabaseMetaData metaData = connection.getMetaData();

            // 输出数据库信息
            System.out.println("Database Product Name: " + metaData.getDatabaseProductName());
            System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion());
            System.out.println("Driver Name: " + metaData.getDriverName());
            System.out.println("Driver Version: " + metaData.getDriverVersion());

            // 关闭资源
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. Using stored procedures

A stored procedure is a set of precompiled SQL statements that are stored in the database and can improve application performance. Here is a simple example that demonstrates how to call a MySQL stored procedure:

Suppose we have a get_user_countstored procedure called that gets usersthe number of records in a table:

DELIMITER //
CREATE PROCEDURE get_user_count(OUT count INT)
BEGIN
  SELECT COUNT(*) INTO count FROM users;
END //
DELIMITER ;

Here's how to call this stored procedure using Java:

import java.sql.*;

public class JdbcStoredProcedureExample {
    public static void main(String[] args) {
        try {
            // 加载数据库驱动并连接到数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            // 调用存储过程
            CallableStatement callableStatement = connection.prepareCall("{CALL get_user_count(?)}");
            callableStatement.registerOutParameter(1, Types.INTEGER);
            callableStatement.execute();

            // 获取存储过程返回的结果
            int userCount = callableStatement.getInt(1);
            System.out.println("User count: " + userCount);

            // 关闭资源
            callableStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5. Using RowSet

RowSetIs a scrollable, updatable Java object that contains data corresponding to a database table. Here is a simple example showing how to use it JdbcRowSet:

First, add javax.sql.rowsetdependencies:

Maven:

<dependency>
    <groupId>javax.sql</groupId>
    <artifactId>rowset</artifactId>
    <version>1.2</version>
</dependency>

Gradle:

implementation 'javax.sql:rowset:1.2'

Then, use JdbcRowSet:

import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.ResultSetMetaData;

public class JdbcRowSetExample {
    public static void main(String[] args) {
        try {
            // 创建JdbcRowSet
            JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
            rowSet.setUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true");
            rowSet.setUsername("root");
            rowSet.setPassword("mypassword");

            // 执行查询
            rowSet.setCommand("SELECT * FROM users");
            rowSet.execute();

            // 处理查询结果
            ResultSetMetaData metaData = rowSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (rowSet.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    System.out.print(metaData.getColumnName(i) + ": " + rowSet.getObject(i) + " ");
                }
                System.out.println();
            }

            // 关闭资源
            rowSet.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

These examples should help you better understand various aspects of Java database programming. In actual projects, you may need to adjust and optimize according to specific needs. Hope this information can help you more in Java database programming. Recommended reading:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

Guess you like

Origin blog.csdn.net/u010671061/article/details/131003184