线程

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处,我原先是写了关闭数据库连接,但是如果是同个线程再次使用连接就会出错,如果不关闭数据库连接,那会造成泄露,这一步该怎么修改会好一点呢,当然,使用数据库连接池是一个好的办法,还有没有别的方法呢
...全文
35 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

81,090

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧