天天看點

自己寫一個資料庫連接配接工具類

最近剛複習了一下JDBC相關的知識,這裡來寫一個mysql資料庫連接配接工具類來練習一下。

在jdbc連接配接資料庫時,Connection對象是非常稀有的資源,用完後必須馬上釋放,如果Connection不能及時、正确的關閉,極易導緻系統當機。Connection的使用原則是盡量晚建立,盡量早的釋放。

是以在一個項目中,如何正确的去管理Connection對象就顯得尤為重要。資料庫連接配接工具類需要包括一下功能:

(1)為了實作解耦合,我們提供配置檔案的方式來進行資料庫參數的配置

(2)實作一個類,用來提供資料庫連接配接

(3)實作關閉資料庫連接配接

首先我們建立一個項目:/MysqlUtil,并導入mysql-connector-java-5.1.40-bin.jar這個jar包到項目中

然後在類加載目錄下建立一個配置檔案:/MysqlUtil/src/test.properties

//資料庫驅動的名稱,可以根據不同的資料庫進行相應的修改
drivername=com.mysql.jdbc.Driver
//資料庫的url
url=jdbc:mysql://localhost:3306/test
//使用者名
username=root
//密碼
password=root
           

資料庫的URL用于辨別資料庫的位置,程式員通過URL位址告訴JDBC程式連接配接哪個資料庫,URL的寫法為:

jdbc:mysql:[]//localhost:3306/test ?參數名:參數值

協定 子協定 主機 端口 資料庫

常用資料庫URL位址的寫法:

Oracle寫法:jdbc:oracle:thin:@localhost::sid
SqlServer—jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sid
MySql—jdbc:mysql://localhost:3306/sid
Mysql的url位址的簡寫形式: jdbc:mysql:///sid
常用屬性:useUnicode=true&characterEncoding=UTF-
           

建立一個工具類/MysqlUtil/src/com/chen/util/mysqlConnUtil.java

我們這個類需要實作的功能主要包括:

(1) 讀取配置檔案

(2) 加載資料庫驅動

(3) 擷取資料庫連接配接

(4)關閉資料庫連接配接

其中,讀取配置檔案應該在類加載時完成,我們可以考慮把代碼放在靜态代碼塊中,并建立兩個靜态函數分别來進行資料庫連接配接和關閉的操作 ,代碼如下:

package com.chen.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class mysqlConnUtil {
    private static Properties properties = new Properties();

    static{
        String path = mysqlConnUtil.class.getClassLoader().getResource("test.properties").getPath();
        try {
            properties.load(new FileInputStream(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConn(){
            Connection conn = null;
            try {
                Class.forName(properties.getProperty("drivername"));
                conn =  DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username") , "");
            } catch (Exception e) {
                e.printStackTrace();
            }

        return conn;

    }


    public static void release(Connection conn,Statement stat,ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally{
                rs = null;
            }
        }
        if(stat != null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally{
                stat = null;
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally{
                conn = null;
            }
        }

    }
}