DBUtilでjdbcをカプセル化

6742 ワード

db.propertiesはsrcディレクトリの下に配置されます
public class DBUtil {
    private static Properties prop = new Properties();

    static {
        try {
            prop.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
            //       (    )
            Class.forName(prop.getProperty("driverClassName"));
        } catch (Exception e) {
            System.out.println("  db.properties        ....");
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            String url = prop.getProperty("url");
            String username = prop.getProperty("username");
            String password = prop.getProperty("password");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            System.out.println("         ...");
            e.printStackTrace();
        }
        return conn;
    }

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

    }