Druid 數據庫連接池的工具類使用

一、定義工具類

1)定義一個類 JDBCUtils
(2)提供靜態代碼塊加載配置文件,初始化連接池對象
(3)提供方法
		* 獲取連接方法:通過數據庫連接池獲取連接
		* 釋放資源
		* 獲取連接池的方法
public class JDBCUtils {

    //1.定義成員變量 DataSource
    private static DataSource ds ;

    static{
        try {
            //1.加載配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.獲取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取連接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 釋放資源
     */
    public static void close(Statement stmt,Connection conn){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();//歸還連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

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


        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();//歸還連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 獲取連接池方法
     */

    public static DataSource getDataSource(){
        return  ds;
    }
}

二、使用工具類

/**
 * 使用新的工具類
 */
public class DruidDemo {

    public static void main(String[] args) {
        /*
         * 完成添加操作:給account表添加一條記錄
         */
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            //1.獲取連接
            conn = JDBCUtils.getConnection();
            //2.定義sql
            String sql = "insert into account values(null,?,?)";
            //3.獲取pstmt對象
            pstmt = conn.prepareStatement(sql);
            //4.給?賦值
            pstmt.setString(1,"王五");
            pstmt.setDouble(2,3000);
            //5.執行sql
            int count = pstmt.executeUpdate();
            System.out.println(count);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6. 釋放資源
            JDBCUtils.close(pstmt,conn);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章