Java怎么做到代码重用
Java如何做到代码重用
首先在公共类写好数据库连接和关闭方法:
public static Connection getConnection(){ Connection conn = null; try { Context ic = new InitialContext(); DataSource source = (DataSource)ic.lookup("java:comp/env/jdbc/ownHome"); conn = source.getConnection(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } /** * 关闭连接 * @param conn */ public static void closeConnection(Connection conn){ try { if(conn != null || (!conn.isClosed())){ conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭命令 * @param ps */ public static void closeStatement(PreparedStatement ps){ try { if(ps != null){ ps.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭结果集 * @param rs */ public static void closeStatement(ResultSet rs){ try { if(rs != null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); } }
然后 我们把一些获取集合的公共部分提取出来:PreparedStatement 和 SQL语句
public static PreparedStatement makeState(String sql, Object... params) throws Exception { PreparedStatement pstmt = getConnection().prepareStatement(sql); for (int i = 0; i < params.length; i++) { pstmt.setObject(i + 1, params[i]); } return pstmt; }
这样我们就只用传入任何个数,任何类型的参数和SQL语句就行(注意:sql如果有参数必须是使用“?"标记,也可无参,只用传入SQL语句即可,这就是三点水的好处)
如:我们写了一个集合方法
public static List<Article> getArticlesBySql(String sql,Object...params){ PreparedStatement ps = null; ResultSet rs = null; List<Article> list = new ArrayList<Article>(); try { ps = makeState(sql, params); } catch (Exception e1) { e1.printStackTrace(); } try { rs = ps.executeQuery(); while (rs.next()) { Article article = new Article(); article.setArticleId(rs.getInt("articleId")); article.setContent(rs.getString("content")); article.setTitle(rs.getString("title")); article.setType(rs.getInt("type")); article.setWriteDate(rs.getString("writeDate")); article.setWriter(rs.getString("writer")); list.add(article); } } catch (SQLException e) { e.printStackTrace(); }finally{ GetDataBean.closeStatement(rs); GetDataBean.closeStatement(ps); GetDataBean.closeConnection(getConnection()); } return list; }
这个集合就可以重复使用:
/** * 获取所有的标题(int)by type) */ public static List<Article> getArticles(int type){ String sql = "select * from article where type=?"; return GetDataBean.getArticlesBySql(sql, type); } /** * 获取所有的标题((int)by type,(String)by usrname) */ public static List<Article> getArticles(int type,String username){ String sql = "select * from article where type=? and writer=?"; return GetDataBean.getArticlesBySql(sql, type, username); } /** * 搜索 * @param type * @param title * @param writer * @return */ public static List<Article> getArticles(int type,String title,String writer){ String sql = "select * from article where type=? and writer=? and title=? "; return GetDataBean.getArticlesBySql(sql, type, writer, title); }