Javaweb笔记(十三):针对前两篇笔记中使用的工具类做记录

2019-07-17  本文已影响0人  睿丶清

JDBCUtils 操作数据库的工具类:

public class JDBCUtils {

    /**
     * 连接数据库
     * 
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {

        //properties为配置文件对象 配置文件中包含数据库驱动名称,数据库地址,数据库用户名称即密码
        Properties properties = PropertiesUtils.getProperties();
        Class.forName(properties.getProperty("drivername"));
        return DriverManager.getConnection(properties.getProperty("dburl"), properties.getProperty("dbuser"),
                properties.getProperty("dbpwd"));
    }

    /**
     * 关闭数据库和对应的流
     * @param rs
     * @param st
     * @param connection
     */
    public static void closeConnection(ResultSet rs, Statement st, Connection connection) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

PropertiesUtils 实现java代码获取本地配置文件

/**
 * java代码加载配置配置清单文件 即(config.properties)
 * @author wujinli
 *
 */
public class PropertiesUtils {

    public static Properties getProperties() {
        InputStream inStream=JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
        Properties properties=new Properties();
        try {
            properties.load(inStream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return properties;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读