线程

hkwzhh 2015-08-07 09:13:11

public class CommUtil {
public static ThreadLocal<Connection> conn = new ThreadLocal<Connection>();

public static Connection getConnection() throws Exception{
if(conn.get() == null){
InputStream inputStream = CommUtil.class.getClassLoader()
.getResourceAsStream("database.properties");
Properties p = new Properties();

p.load(inputStream);


Class.forName(p.getProperty("driver"));
Connection con = DriverManager.getConnection(p.getProperty("url"),
p.getProperty("username"), p.getProperty("password"));
conn.set(con);
//1,return con;
return conn.get();

}

return conn.get();
}

/*static {
InputStream inputStream = CommUtil.class.getClassLoader()
.getResourceAsStream("database.properties");
Properties p = new Properties();
try {
p.load(inputStream);
} catch (IOException e1) {
e1.printStackTrace();

}
try {
Class.forName(p.getProperty("driver"));
Connection con = DriverManager.getConnection(p.getProperty("url"),
p.getProperty("username"), p.getProperty("password"));
conn.set(con);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}*/

private static void closeCon(ResultSet rs, PreparedStatement st,
Connection con) throws SQLException {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}

public static List<String[]> getStrsList(String sql) throws Exception {
List<String[]> ls = new ArrayList<String[]>();
Connection connection = null;

ResultSet rs = null;
PreparedStatement ps = null;
connection = getConnection();
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
ls = transtoStrsList(rs);
//2,closeCon(rs, ps, connection);
return ls;
}

// 将结果级转成List
private static List<String[]> transtoStrsList(ResultSet rs)
throws SQLException {
List<String[]> ls = new ArrayList<String[]>();
int cols = rs.getMetaData().getColumnCount();
while (rs.next()) {
String strs[] = new String[cols];
for (int i = 1; i <= cols; i++) {

strs[i - 1] = rs.getString(i);
}
ls.add(strs);
}
return ls;

}
}

各位大神好,小弟初入Java,以上代码是自己写的一个简易数据库连接类,代码笨拙,提出以下疑问:
1,在1处,如果是return con,会不会造成内存泄露或者不可预见 的错误
2,在2处,我原先是写了关闭数据库连接,但是如果是同个线程再次使用连接就会出错,如果不关闭数据库连接,那会造成泄露,这一步该怎么修改会好一点呢,当然,使用数据库连接池是一个好的办法,还有没有别的方法呢
...全文
5 点赞 收藏 回复
写回复
回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
相关推荐
发帖
Web 开发
创建于2007-09-28

8.0w+

社区成员

Java Web 开发
申请成为版主
帖子事件
创建了帖子
2015-08-07 09:13
社区公告
暂无公告