81,090
社区成员
发帖
与我相关
我的任务
分享
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;
}
}