1. 程式人生 > >java之資料庫相關

java之資料庫相關

import java.sql.*;
import java.util.ResourceBundle;
//注意:dbinfo.properties要和該載入檔案放到一個目錄下,不用寫全稱,只需要寫dbinfo即可
public class DBUtils {

    private static String driverClass;
    private static String url;

    static {
        //此物件是用來載入properties檔案資料的
        ResourceBundle rb = ResourceBundle.getBundle("dbinfo");

        driverClass 
= rb.getString("driverClass"); url = rb.getString("url"); try { Class.forName(driverClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws Exception { return DriverManager.getConnection(url); }
public static void closeAll(ResultSet resultSe, Statement statement, Connection connection){ if (resultSe != null){ try { resultSe.close(); } catch (SQLException e) { e.printStackTrace(); } } //resultSe = null;
if (statement != null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } //statement = null; if (connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } // connection = null; } }