欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java自定義JDBC實(shí)現(xiàn)連接池

 更新時(shí)間:2024年02月22日 09:36:23   作者:Mr-Apple  
本文主要介紹了java自定義JDBC實(shí)現(xiàn)連接池,包含實(shí)現(xiàn)JDBC連接池以及SQLException?異常的處理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

簡單上手

使用 JDBC 來執(zhí)行 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("成功連接到數(shù)據(jù)庫");

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

            // 打印查詢結(jié)果
            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("更新操作影響的行數(shù): " + rowsAffected);

        } catch (SQLException e) {
            System.out.println("數(shù)據(jù)庫操作失敗:" + e.getMessage());
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                    System.out.println("成功關(guān)閉數(shù)據(jù)庫連接");
                } catch (SQLException e) {
                    System.out.println("關(guān)閉數(shù)據(jù)庫連接失?。? + e.getMessage());
                }
            }
        }
    }
}

下面展示一些 內(nèi)聯(lián)代碼片

// A code blockvar foo = 'bar';

// An highlighted blockvar foo = 'bar';

實(shí)現(xiàn)JDBC連接池

JDBC 數(shù)據(jù)庫連接池的示例代碼:

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; // 最大連接數(shù)限制
    private static final long CONNECTION_TIMEOUT = 5000; // 連接超時(shí)時(shí)間,單位毫秒

    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("數(shù)據(jù)庫連接池初始化完成,當(dāng)前連接數(shù): " + 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("獲取數(shù)據(jù)庫連接超時(shí)");
            }
        }

        Connection connection = availableConnections.remove(availableConnections.size() - 1);
        usedConnections.add(connection);
        System.out.println("獲取數(shù)據(jù)庫連接,當(dāng)前連接數(shù): " + availableConnections.size());
        return connection;
    }

    public synchronized void releaseConnection(Connection connection) {
        if (connection != null) {
            usedConnections.remove(connection);
            availableConnections.add(connection);
            notifyAll();
            System.out.println("釋放數(shù)據(jù)庫連接,當(dāng)前連接數(shù): " + availableConnections.size());
        }
    }
}

在上面的示例代碼中,我們?cè)黾恿俗畲筮B接數(shù)限制和連接超時(shí)處理機(jī)制。當(dāng)連接池中的連接數(shù)達(dá)到最大值時(shí),新請(qǐng)求會(huì)等待一段時(shí)間,如果超過連接超時(shí)時(shí)間仍未獲取到連接,則會(huì)拋出 SQLException 異常表示獲取連接超時(shí)。同時(shí),我們還通過控制臺(tái)輸出連接池的狀態(tài)信息,方便跟蹤連接的獲取和釋放情況。

測試

測試數(shù)據(jù)庫連接池的最大連接數(shù)限制和連接超時(shí)處理機(jī)制:

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);

        // 模擬多個(gè)線程同時(shí)請(qǐng)求數(shù)據(jù)庫連接
        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 + " 獲取到數(shù)據(jù)庫連接");
                // 模擬操作持有連接的時(shí)間
                Thread.sleep(3000);
                System.out.println("Worker " + workerId + " 完成操作,釋放數(shù)據(jù)庫連接");
            } catch (SQLException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

關(guān)于SQLException

SQLException 是 Java 中的一個(gè)異常類,用于表示與數(shù)據(jù)庫相關(guān)的異常。當(dāng)使用 JDBC 連接數(shù)據(jù)庫時(shí),很多操作都可能會(huì)拋出 SQLException 異常,比如連接數(shù)據(jù)庫、執(zhí)行查詢、更新數(shù)據(jù)等過程中出現(xiàn)的錯(cuò)誤。

SQLException 是 java.sql.SQLException 類的全名,它是 java.sql 包中的一個(gè)類,專門用于處理數(shù)據(jù)庫操作可能出現(xiàn)的異常情況。該異常類提供了一系列方法,用于獲取關(guān)于異常的詳細(xì)信息,比如異常消息、SQL 狀態(tài)碼、引起異常的原因等,方便開發(fā)人員進(jìn)行異常處理和調(diào)試。

在使用 JDBC 連接數(shù)據(jù)庫時(shí),通常會(huì)在代碼中捕獲 SQLException 異常,并根據(jù)具體情況進(jìn)行異常處理,比如輸出異常信息、回滾事務(wù)、關(guān)閉連接等操作,以確保程序的穩(wěn)定性和可靠性。

下面是一個(gè)簡單的示例,演示了如何捕獲并處理 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);
            // 執(zhí)行數(shù)據(jù)庫操作...
        } catch (SQLException e) {
            System.out.println("數(shù)據(jù)庫操作失?。? + e.getMessage());
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    System.out.println("關(guān)閉數(shù)據(jù)庫連接失敗:" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}

在上面的示例中,我們?cè)谶B接數(shù)據(jù)庫和關(guān)閉數(shù)據(jù)庫連接的過程中捕獲了 SQLException 異常,并通過 e.getMessage() 方法獲取異常信息進(jìn)行輸出。這樣可以幫助我們更好地理解和處理與數(shù)據(jù)庫交互過程中可能出現(xiàn)的異常情況。

到此這篇關(guān)于java自定義JDBC實(shí)現(xiàn)連接池的文章就介紹到這了,更多相關(guān)java JDBC連接池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java設(shè)計(jì)實(shí)現(xiàn)一個(gè)針對(duì)各種類型的緩存

    Java設(shè)計(jì)實(shí)現(xiàn)一個(gè)針對(duì)各種類型的緩存

    這篇文章主要為大家詳細(xì)介紹了Java如何設(shè)計(jì)實(shí)現(xiàn)一個(gè)針對(duì)各種類型的緩存,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下
    2023-11-11
  • 使用Java實(shí)現(xiàn)MapReduce詞頻統(tǒng)計(jì)示例代碼

    使用Java實(shí)現(xiàn)MapReduce詞頻統(tǒng)計(jì)示例代碼

    這篇文章主要介紹了使用Java實(shí)現(xiàn)MapReduce詞頻統(tǒng)計(jì)的相關(guān)資料,通過詞頻統(tǒng)計(jì)示例來展示MapReduce的運(yùn)行機(jī)制,涵蓋了Mapper和Reducer的實(shí)現(xiàn),并說明了如何配置和執(zhí)行MapReduce作業(yè),需要的朋友可以參考下
    2024-11-11
  • Jmeter中正則表達(dá)式提取器使用詳解

    Jmeter中正則表達(dá)式提取器使用詳解

    本文主要介紹了Jmeter中正則表達(dá)式提取器使用詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 使用sharding-jdbc實(shí)現(xiàn)水平分表的示例代碼

    使用sharding-jdbc實(shí)現(xiàn)水平分表的示例代碼

    本文主要介紹了sharding-jdbc實(shí)現(xiàn)水平分表,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • java中Calendar與Date類型互相轉(zhuǎn)換的方法

    java中Calendar與Date類型互相轉(zhuǎn)換的方法

    這篇文章主要介紹了java中Calendar與Date類型互相轉(zhuǎn)換的方法,Calendar與Date類型是我們?nèi)粘i_發(fā)中常用的兩種數(shù)據(jù)類型,它們用于不同的場景,兩者具有不同的方法,接下來通過實(shí)例給大家詳解,需要的朋友可以參考下
    2022-09-09
  • Java垃圾回收jconsole分析

    Java垃圾回收jconsole分析

    這篇文章主要為大家介紹了Java垃圾回收jconsole分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • Java編程環(huán)境搭建和變量基本使用圖文教程

    Java編程環(huán)境搭建和變量基本使用圖文教程

    這篇文章主要介紹了Java編程環(huán)境搭建和變量基本使用,結(jié)合圖文形式詳細(xì)分析了java編程語言環(huán)境搭建、配置、變量、注釋的基本使用方法,需要的朋友可以參考下
    2020-02-02
  • java使用JNA(Java Native Access)調(diào)用dll的方法

    java使用JNA(Java Native Access)調(diào)用dll的方法

    java使用JNA(Java Native Access)調(diào)用windows系統(tǒng)的dll文件的例子
    2013-11-11
  • 基于Java?GUI?事件處理方式

    基于Java?GUI?事件處理方式

    這篇文章主要介紹了基于Java?GUI?事件處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • springboot2.x引入feign踩的坑及解決

    springboot2.x引入feign踩的坑及解決

    這篇文章主要介紹了springboot2.x引入feign踩的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01

最新評(píng)論