1. 程式人生 > 其它 >一個JDBC封裝工具類

一個JDBC封裝工具類

前言

在使用Java操作MySQL資料庫的時候,會使用到JDBC驅動,但是在每次連線並使時都需要建立一堆的類和相關引數,還是有點麻煩的。在這裡有一個封裝好的JDBC工具類,裡面包含了Java連線MySQL資料庫時所需要的的屬性和方法,程式碼如下。

JDBCUtils.java

/**
 * 對JDBC進行封裝的工具類
 * 完成MySQL的連線和資源關閉
 */
public class JDBCUtils {
    //定義相關的連線屬性
    private static String user;//使用者名稱
    private static String password;//密碼
    private static String url;//url
    private static String driver;//驅動名

    //在static程式碼塊進行初始化
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\mysql.properties"));//改路徑是配置檔案的路徑
            //讀取相關的屬性值
            user = properties.getProperty("user");//獲取使用者名稱
            password = properties.getProperty("password");//獲取密碼
            url = properties.getProperty("url");//獲取連線URL
            driver = properties.getProperty("driver");//獲取驅動的路徑
        } catch (IOException e) {
            //在實際開發中,可以這樣處理IOException
            //編譯異常-->執行處理
            //呼叫者可以選擇捕獲該異常,也可以選擇預設處理,比較方便
            throw new RuntimeException(e);
        }
    }

    //編寫方法,連線資料庫,返回Connection給使用工具類的程式
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //關閉相關資源
    /**
     * ResultSet 結果集
     * Statement 或 PreparedStatement
     * Connection
     * 如果需要關閉資源,就傳入物件,否則傳入null
     */
    public static  void close(ResultSet set, Statement statement,Connection connection){
        //判斷是否為空
        try {
            if (set != null){
                set.close();
            }
            if (statement != null){
                statement.close();
            }
            if (connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

配置檔案

注意:配置檔案的 " = " 兩邊不能有空格

user=資料庫使用者名稱
password=密碼
url=jdbc:mysql://localhost:3306/test
driver=com.mysql.jdbc.Driver

使用例項

/**
 * 使用JDBCUtils工具類
 */
public class JDBCUtils_Use {
    public static void main(String[] args) {
        //得到一個連線物件
        Connection connection = JDBCUtils.getConnection();
        //組織一個SQL語句
        // String sql = "update admin set name = ? where id = ?";
        String sql1 = "select * from `admin`";
        PreparedStatement preparedStatement = null;//擴大作用域
        ResultSet set = null;
        //建立一個PreparedStatement物件
        try {
            preparedStatement = connection.prepareStatement(sql1);
            //給佔位符賦值
//            preparedStatement.setString(1,"張三");
//            preparedStatement.setInt(2,1);
            //開始執行SQL語句
            int rows = preparedStatement.executeUpdate();//這裡的會返回一個受影響行數的int值,在JDBC中,使用不同的 preparedStatement 的方法,會有不同的返回值,比如下面的 executeQuery() 方法是一個返回一個結果集,可以通過遍歷的方法將結果集的內容打印出來。
            set = preparedStatement.executeQuery();
//            System.out.println(rows+" 行受到影響");
            //得到結果集
            //遍歷該結果集
            while (set.next()){
                int id = set.getInt("id");
                String name = set.getString("name");
                System.out.println(id +"\t"+ name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //關閉資源
            JDBCUtils.close(set,preparedStatement,connection);
        }
    }
}