maven+JDBC中抽象出獲取連接和釋放資源接口的三種方式

注:此博客不再更新,所有最新文章將發表在個人獨立博客limengting.site。分享技術,記錄生活,歡迎大家關注

目錄結構:
這裏寫圖片描述

**Version 1:**只抽象出方法封裝成一個類,但是仍然是硬編碼,數據庫的四個參數直接寫在類中

JDBCUtils_V1.java中的內容:

package sunnie;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 提供獲取連接和釋放資源的 方法
 * @version V1.0
 */

public class JDBCUtils_V1 {

    /**
     * 獲取連接方法
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            //Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sunnie?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true", "root", "password");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

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

    }
}

**Version 2:**把數據庫的四個參數寫在.properties文件中國,使用ResourceBundle對象的getBundle()方法加載properties文件

db.properties中的內容:

#driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sunnie?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true
username=root
password=password

JDBCUtils_V2.java中的內容:

package sunnie;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * 提供獲取連接和釋放資源的方法
 *
 * @version V2.0
 */
public class JDBCUtils_V2 {
    //private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /**
     * 靜態代碼塊加載配置文件信息
     */
    static {
    //getBundle中寫的是不加.properties後綴的文件名
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        //driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");
    }

    /**
     * 獲取連接方法
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            //Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

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

    }

    public static void main(String[] args) {
        testAdd();
    }

    public static void testAdd() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 1.獲取連接
            conn = JDBCUtils_V2.getConnection();
            // 2.編寫sql語句
            String sql = "insert into user values(null,?,?)";
            // 3.獲取執行sql語句對象
            pstmt = conn.prepareStatement(sql);
            // 4.設置參數
            pstmt.setString(1, "sunnie");
            pstmt.setString(2, "limengting");
            // 5.執行插入操作
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println("添加成功!");
            } else {
                System.out.println("添加失敗!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 6.釋放資源
            JDBCUtils_V2.release(conn, pstmt, null);
        }
    }
}

**Version 3:**使用類加載器(ClassLoader)加載資源把配置文件以流的方式獲取,再使用Properties對象的load方法加載指定的流

InputStream is = xxx.class.getClassLoader().getResourceAsStream("xx.properties");
Properties props = new Properties();
props.load(is);

//獲取參數
url = props.getProperty("jdbc.url");
...

JDBCUtils_V3.java中的內容:

package sunnie;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * 提供獲取連接和釋放資源的 方法
 * @version V3.0
 */
public class JDBCUtils_V3 {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /**
     * 靜態代碼塊加載配置文件信息
     */
    static {
        try {
            // 1.通過當前類獲取類加載器
            ClassLoader classLoader = JDBCUtils_V3.class.getClassLoader();
            // 2.通過類加載器的方法獲得一個輸入流
            InputStream is = classLoader.getResourceAsStream("db.properties");
            // 3.創建一個properties對象
            Properties props = new Properties();
            // 4.加載輸入流
            props.load(is);
            // 5.獲取相關參數的值
            driver = props.getProperty("driver");
            url = props.getProperty("url");
            username = props.getProperty("username");
            password = props.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 獲取連接方法
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            //Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

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

    }
}

從配置文件中讀取參數需要注意的問題:
.properties配置文件放在\src\main\resources\db.properties位置,直接寫"xx.properties"

junit測試:

package sunnietest;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

import sunnie.JDBCUtils_V1;
import sunnie.JDBCUtils_V2;
import sunnie.JDBCUtils_V3;

/**
 * 測試工具類
 */
public class TestUtils {
	/**
	 * 根據id更新用戶信息方法
	 * 測試JDBCUtils_V3
	 */
	@Test
	public void testUpdateById() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			// 1.獲取連接
			conn = JDBCUtils_V3.getConnection();
			// 2.編寫sql語句
			String sql = "update user set password=? where id=?";
			// 3.獲取執行sql語句對象
			pstmt = conn.prepareStatement(sql);
			// 4.設置參數
			pstmt.setString(1, "666");
			pstmt.setInt(2, 3);
			// 5.執行更新操作
			int row = pstmt.executeUpdate();
			if (row > 0) {
				System.out.println("更新成功!");
			} else {
				System.out.println("更新失敗!");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			// 6.釋放資源
			JDBCUtils_V3.release(conn, pstmt, null);
		}
	}

	/**
	 * 根據id刪除信息方法
	 * 測試JDBCUtils_V3
	 */
	@Test
	public void testDeleteById() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			// 1.獲取連接
			conn = JDBCUtils_V3.getConnection();
			// 2.編寫sql語句
			String sql = "delete from user where id=?";
			// 3.獲取執行sql語句對象
			pstmt = conn.prepareStatement(sql);
			// 4.設置參數
			pstmt.setInt(1, 4);
			// 5.執行刪除操作
			int row = pstmt.executeUpdate();
			if (row > 0) {
				System.out.println("刪除成功!");
			} else {
				System.out.println("刪除失敗!");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			// 6.釋放資源
			JDBCUtils_V3.release(conn, pstmt, null);
		}
	}

	/**
	 * 添加用戶信息方法
	 * 測試JDBCUtils_V2
	 */
	@Test
	public void testAdd() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			// 1.獲取連接
			conn = JDBCUtils_V2.getConnection();
			// 2.編寫sql語句
			String sql = "insert into user values(null,?,?)";
			// 3.獲取執行sql語句對象
			pstmt = conn.prepareStatement(sql);
			// 4.設置參數
			pstmt.setString(1, "lisi");
			pstmt.setString(2, "hehe");
			// 5.執行插入操作
			int row = pstmt.executeUpdate();
			if (row > 0) {
				System.out.println("添加成功!");
			} else {
				System.out.println("添加失敗!");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			// 6.釋放資源
			JDBCUtils_V2.release(conn, pstmt, null);
		}
	}

	/**
	 * 根據id查詢用戶信息
	 * 測試JDBCUtils_V1
	 */
	@Test
	public void testFindUserById() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			// 1.獲取連接
			conn = JDBCUtils_V1.getConnection();
			// 2.編寫sql語句
			String sql = "select * from user where id=?";
			// 3.獲取執行sql語句對象
			pstmt = conn.prepareStatement(sql);
			// 4.設置參數
			pstmt.setInt(1, 2);
			// 5.執行查詢操作
			rs = pstmt.executeQuery();
			// 6.處理結果集
			while (rs.next()) {
				System.out.println(rs.getString(2) + "----" + rs.getString("password"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 7.釋放資源
			JDBCUtils_V1.release(conn, pstmt, rs);
		}
	}
}

pom.xml添加依賴:

<dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章