JDBC实现连接池

简单上手

使用 JDBC 来执行 SQL 查询和更新操作

import java.sql.*;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database_name";
        String username = "your_username";
        String password = "your_password";

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("成功连接到数据库");

            // 查询操作
            String query = "SELECT * FROM your_table_name";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);

            // 打印查询结果
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }

            // 更新操作
            String update = "UPDATE your_table_name SET name = 'New Name' WHERE id = 1";
            int rowsAffected = statement.executeUpdate(update);
            System.out.println("更新操作影响的行数: " + rowsAffected);

        } catch (SQLException e) {
            System.out.println("数据库操作失败:" + e.getMessage());
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                    System.out.println("成功关闭数据库连接");
                } catch (SQLException e) {
                    System.out.println("关闭数据库连接失败:" + e.getMessage());
                }
            }
        }
    }
}

下面展示一些 内联代码片

// A code blockvar foo = 'bar';
// An highlighted blockvar foo = 'bar';

实现JDBC连接池

JDBC 数据库连接池的示例代码:

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

public class ConnectionPool {
    private static final int MAX_CONNECTIONS = 10; // 最大连接数限制
    private static final long CONNECTION_TIMEOUT = 5000; // 连接超时时间,单位毫秒

    private Vector<Connection> availableConnections = new Vector<>();
    private Vector<Connection> usedConnections = new Vector<>();

    public ConnectionPool(String url, String username, String password) {
        initializeConnectionPool(url, username, password);
    }

    private void initializeConnectionPool(String url, String username, String password) {
        while (!checkIfConnectionPoolIsFull()) {
            availableConnections.add(createNewConnection(url, username, password));
        }
        System.out.println("数据库连接池初始化完成,当前连接数: " + availableConnections.size());
    }

    private synchronized boolean checkIfConnectionPoolIsFull() {
        return (availableConnections.size() + usedConnections.size()) >= MAX_CONNECTIONS;
    }

    private Connection createNewConnection(String url, String username, String password) {
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public synchronized Connection getConnection() throws SQLException {
        long startTime = System.currentTimeMillis();
        while (availableConnections.isEmpty()) {
            try {
                wait(CONNECTION_TIMEOUT);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if ((System.currentTimeMillis() - startTime) >= CONNECTION_TIMEOUT) {
                throw new SQLException("获取数据库连接超时");
            }
        }

        Connection connection = availableConnections.remove(availableConnections.size() - 1);
        usedConnections.add(connection);
        System.out.println("获取数据库连接,当前连接数: " + availableConnections.size());
        return connection;
    }

    public synchronized void releaseConnection(Connection connection) {
        if (connection != null) {
            usedConnections.remove(connection);
            availableConnections.add(connection);
            notifyAll();
            System.out.println("释放数据库连接,当前连接数: " + availableConnections.size());
        }
    }
}

在上面的示例代码中,我们增加了最大连接数限制和连接超时处理机制。当连接池中的连接数达到最大值时,新请求会等待一段时间,如果超过连接超时时间仍未获取到连接,则会抛出 SQLException 异常表示获取连接超时。同时,我们还通过控制台输出连接池的状态信息,方便跟踪连接的获取和释放情况。

测试

测试数据库连接池的最大连接数限制和连接超时处理机制:

public class ConnectionPoolTest {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database_name";
        String username = "your_username";
        String password = "your_password";

        ConnectionPool connectionPool = new ConnectionPool(url, username, password);

        // 模拟多个线程同时请求数据库连接
        for (int i = 0; i < 15; i++) {
            Thread thread = new Thread(new Worker(connectionPool, i));
            thread.start();
        }
    }

    static class Worker implements Runnable {
        private ConnectionPool connectionPool;
        private int workerId;

        public Worker(ConnectionPool connectionPool, int workerId) {
            this.connectionPool = connectionPool;
            this.workerId = workerId;
        }

        @Override
        public void run() {
            try (Connection connection = connectionPool.getConnection()) {
                System.out.println("Worker " + workerId + " 获取到数据库连接");
                // 模拟操作持有连接的时间
                Thread.sleep(3000);
                System.out.println("Worker " + workerId + " 完成操作,释放数据库连接");
            } catch (SQLException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

关于SQLException
SQLException 是 Java 中的一个异常类,用于表示与数据库相关的异常。当使用 JDBC 连接数据库时,很多操作都可能会抛出 SQLException 异常,比如连接数据库、执行查询、更新数据等过程中出现的错误。

SQLExceptionjava.sql.SQLException 类的全名,它是 java.sql 包中的一个类,专门用于处理数据库操作可能出现的异常情况。该异常类提供了一系列方法,用于获取关于异常的详细信息,比如异常消息、SQL 状态码、引起异常的原因等,方便开发人员进行异常处理和调试。

在使用 JDBC 连接数据库时,通常会在代码中捕获 SQLException 异常,并根据具体情况进行异常处理,比如输出异常信息、回滚事务、关闭连接等操作,以确保程序的稳定性和可靠性。

下面是一个简单的示例,演示了如何捕获并处理 SQLException 异常:

import java.sql.*;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database_name";
        String username = "your_username";
        String password = "your_password";

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
            // 执行数据库操作...
        } catch (SQLException e) {
            System.out.println("数据库操作失败:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    System.out.println("关闭数据库连接失败:" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}

在上面的示例中,我们在连接数据库和关闭数据库连接的过程中捕获了 SQLException 异常,并通过 e.getMessage() 方法获取异常信息进行输出。这样可以帮助我们更好地理解和处理与数据库交互过程中可能出现的异常情况。

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值