JDBC及封裝,DBUtil使用,自定義連接池,c3p0和dbcp連接池使用

本篇包括如下內容:

  • ** 1,JDBC及封裝,**
  • 2,DBUtil使用,
  • 3,自定義連接池,
  • 4,c3p0和dbcp連接池使用

1,JDBC及封裝(Java DataBase Connectivity)
  • 1.1, JDBC的使用
  • 注意使用前需要先引入相應的包
  • 在查詢的時候用PreparedStatement這個比較安全,如果用Statement有插入攻擊的危險
try {
    //1,注冊驅動
    Class.forName("com.mysql.jdbc.Driver");
    
    //2,獲取連接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ivanl?autoReconnect=true&useSSL=false&characterEncoding=utf-8", "root", "0.");
    
    //3,通過連接進行查詢
    PreparedStatement preparedStatement = connection.prepareStatement("select * from t_product");
    ResultSet set = preparedStatement.executeQuery();
    while(set.next()){
        System.out.println(set.getString("name") + "  " + set.getDouble("price"));
    }
    
    //4,關閉資源
    set.close();
    preparedStatement.close();
    connection.close();
    
} catch (Exception e) {
    e.printStackTrace();
}
  • 1.2, JDBC的自定義封裝
  • 既然是對jdbc的封裝,也需要先引入必要的包
  • 因為驅動注冊和獲取連接池以及關閉資源所有的數據庫操作都是一致的,所以驅動注冊和獲取連接池直接用靜態方法進行封裝,只讀取一次,關閉資源傳入參數進行關閉

讀取配置文件資源的時候,如果是java項目,有兩種方式:Properties和ResourceBundle,代碼有體現

package im.jdbcutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;

public class JDBCUtil {
    
    public static String driver;
    public static String url;
    public static String username;
    public static String pwd;
  
    static{
        try {
            /*
            Properties properties = new Properties();
            FileInputStream inputStream = new FileInputStream("src/database.properties");
            properties.load(inputStream);
            driver = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            username = properties.getProperty("user");
            pwd = properties.getProperty("password");
            */

            ResourceBundle bundle = ResourceBundle.getBundle("database");
            driver = bundle.getString("driverClass");
            url = bundle.getString("url");
            username = bundle.getString("user");
            pwd = bundle.getString("password");
            
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            //1,注冊驅動
            Class.forName("com.mysql.jdbc.Driver");
            //2,獲取連接
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/ivanl?autoReconnect=true&useSSL=false&characterEncoding=utf-8", "root", "0.");
        } catch (Exception e) {
            System.out.println("獲取連接失敗");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    public static void closeAll(Connection connection, PreparedStatement statement, ResultSet resultSet){
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (Exception e) {
            System.out.println("結果集資源釋放失敗");
            e.printStackTrace();
        }
        
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (Exception e) {
            System.out.println("sql聲明資源釋放失敗");
            e.printStackTrace();
        }
        
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            System.out.println("連接集資源釋放失敗");
            e.printStackTrace();
        }
    }
}

數據庫配置文件database.properties內容:

driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test01?autoReconnect=true&useSSL=false&characterEncoding=utf-8
user = root
password = 0.

2,DBUtil使用(對JDBC的封裝)
  • DBUtil創建QueryRunner的時候有兩種方式:空參構建和數據庫構建

  • DBUtil有很多種類型的結果集,比如返回數組,字典,模型等等,文檔中都有比較詳細介紹,如果不太懂的話可以看一下文檔

  • DBUtil既然架包,那么在使用的時候必然需要先導包

  • 2.1,空參構建方式,其中在執行語句的時候需要傳入連接,我這里直接使用1.2中封裝方法獲取連接,可以保證只獲取一次*
Connection connection = JDBCUtil.connection;
String sqlStr = "insert into t_ivanl001 (name, age, num) values (?, ?, ?)";
QueryRunner queryRunner = new QueryRunner();
try {
     Object[] params = {name, age, num};
     queryRunner.update(connection, sqlStr, params);
} catch (SQLException e) {
    System.out.println("數據插入失??!");
    e.printStackTrace();
} 
DbUtils.closeQuietly(connection);
  • 2.2,數據庫構建構建方式,構建時候需要直接傳入一個數據源,數據源可以通過c3p0或dbcp連接池獲得,這是后面的內容,這里先不涉及*
QueryRunner runner = new QueryRunner(DBCPUtil.getDataSource());

try {
     List<Product> products = runner.query("select * from product", new BeanListHandler<Product>(Product.class));
     System.out.println(products);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    
}

3,自定義連接池(使用裝飾者模式進行加強)
//1,自定義連接池
/*
 * 對JDBC連接的封裝,也就是自定義連接池
 * 其他一些方法也需要重寫,但是不需要任何改變,所以這里就沒有貼出來
 */
public class JDBCDatasource implements DataSource {
    private static LinkedList<Connection> connections = new LinkedList<Connection>();
    //往連接池中添加連接
    static{
        for(int i=0;i<5;i++){
            Connection connection = JDBCUtil.getConnection();
            JDBCConnection theConnection = new JDBCConnection(connections, connection);
            connections.add(theConnection);
        }
    }
    //重寫這一個方法,如果沒有增強過connection的話,需要調用這個方法歸還連接到連接池中
    @Override
    public Connection getConnection() throws SQLException {
        if (connections.size() == 0) {
            for(int i=0;i<5;i++){
                Connection connection = JDBCUtil.getConnection();
                JDBCConnection theConnection = new JDBCConnection(connections, connection);
                connections.add(theConnection);
            }
        }
        return connections.removeFirst();
    }
     //新增一個方法
    public void returnConnection(Connection connection){
        connections.add(connection);
    }
}

//2,自定義連接類,實現相應的方法,并在自定義的連接池中進行包裝,具體看1中的代碼
//其他一些不需要修改的覆蓋方法這里不再貼出
public class JDBCConnection implements Connection {
    private Connection connection;
    private LinkedList<Connection> connections;
    public JDBCConnection(List<Connection> connections, Connection connection) {
        this.connections = (LinkedList<Connection>) connections;
        this.connection = connection;
    }
    //如果想要在關閉的時候添加到連接池,那么需要把連接池傳進來,傳進來最好的時候就是創建的時候
    @Override
    public void close() throws SQLException {
        System.out.println("here here!");
        connections.add(connection);
    }
    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }
}

//測試
JDBCDatasource datasource = new JDBCDatasource();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
    connection = datasource.getConnection();
    preparedStatement = connection.prepareStatement("select * from product;");
    resultSet = preparedStatement.executeQuery();
    while(resultSet.next()){
        System.out.println(resultSet.getString("pname"));
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //這行代碼中封裝了connection.close()方法
    JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}
4,c3p0和dbcp連接池使用(連接池可以提高數據庫使用效率)
  • 4.1,c3p0

需要導入包和配置文件
使用代碼如下:
配合DBUtils使用的時候可以直接傳入連接池進行使用,也可以傳入連接使用,見上面的DBUtils的使用

//也可以把c3p0封裝后直接獲取連接池和連接,我這里直接使用
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

DataSource dataSource = new ComboPooledDataSource();
try {
    connection = dataSource.getConnection();
    String sqlStr = "select * from product";
    preparedStatement = connection.prepareStatement(sqlStr);
    resultSet = preparedStatement.executeQuery();
    
    while(resultSet.next()){
        System.out.println(resultSet.getString("pname"));
    }
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}

  • 4.2,dbcp

需要導入包和配置properties文件
使用代碼如下:

Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

connection = DBCPUtil.getConnection();
try {
    preparedStatement = connection.prepareStatement("select * from product");
    resultSet = preparedStatement.executeQuery();
    
    while(resultSet.next()){
        System.out.println(resultSet.getString("pname"));
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}

其中上面用到的DBCPUtilde封裝如下:

package im.dbcputils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

/*
 * 這里是使用默認的配置標準進行配置后讀取文件
 */
public class DBCPUtil {

    private static DataSource dataSource;
    
    static{
        try {
            InputStream inputStream = DBCPUtil.class.getClassLoader().getResourceAsStream("database.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public static DataSource getDataSource() {
        return dataSource;
    }
    
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容