/**
- 加载驱动
- 取得连接
- 关闭资源
- @author Administrator
*/
public class DBUtil {
//Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。
不过Properties有特殊的地方,就是它的键和值都是字符串类型。
private static Properties prop = new Properties();
//创建数据源对象dds(dds你就把它当做成数据库连接池对象就行了)
private static DruidDataSource dds = null;
private DBUtil(){}
static{
try {
//db_server.properties
//加载properties属性文件
//获得当前线程中后缀为Properties的资源文件
//currentThread() 获得当前线程的引用
//Thread.currentThread().getContextClassLoader().getResource("")来得到当前的
classpath的绝对路径的URI
prop.load(Thread.currentThread().getContextClassLoader().
getResourceAsStream ("db_server.properties"));
//由数据库连接池工厂,创建一个数据库连接池对象
dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(prop);
}catch (Exception e) {
e.printStackTrace();
}
}
private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
/*
*
* 当service层在调用该方法的时候,t对象中还没有conn,我们需要创建一个conn,
* 将conn存放到t对象中,将conn返回
*
* 当dao层在调用该方法的时候,t对象中已经有conn了(service层存的),
* 直接从t中取出conn返回即可
*
* set
* get
* remove
*
*/
public static Connection getConn() throws SQLException{
Connection conn = t.get();
if(conn==null){
//conn = DriverManager.getConnection(URL, USER, PASSWORD);
//从dds中取连接
conn = dds.getConnection();
t.set(conn);
}
return conn;
}
//关闭资源
public static void myClose(Connection conn,PreparedStatement ps,ResultSet rs){
//关闭的顺序为 按照创建的顺序逆序关闭
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
//此时的conn是连接池中连接的形态,将连接放回到连接池中
conn.close();
//关闭连接后,不要忘记将conn从t中移除掉
//这句非常容易忘,必须加
//线程池 pool
//连接池 pool
t.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Java本质上只能使用绝对路径来寻找资源。所有的相对路径寻找资源的方法,都不过是一些便利方法。不过是API在底层帮助我们构建了绝对路径,从而找到资源的!
得到classpath和当前类的绝对路径的一些方法
下面是一些得到classpath和当前类的绝对路径的一些方法。你可能需要使用其中的一些方法来得到你需要的资源的绝对路径。
1.FileTest.class.getResource("")
得到的是当前类FileTest.class文件的URI目录。不包括自己!
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/
2.FileTest.class.getResource("/")
得到的是当前的classpath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
3.Thread.currentThread().getContextClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
4.FileTest.class.getClassLoader().getResource("")
得到的也是当前ClassPath的绝对URI路径。
如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
5.ClassLoader.getSystemResource("")
得到的也是当前ClassPath的绝对URI路径。