java_jdbc_可变参数_MetaData

异常处理参考3层解耦

 

ublic class ScrollTest {

	public static void main(String[] args) throws SQLException {
		// TODO Auto-generated method stub
		Object[] params = new Object[]{"username","password"};
		read("select * from t_user where username=? and password=?",params);
	}

	// 可更新结果集
	public static void read(String sql,Object[] params) throws SQLException{
		Connection conn=null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try{
			conn = JdbcUtils.getConnection();
			ps=conn.prepareStatement(sql);
			ParameterMetaData pmd = ps.getParameterMetaData();
			int count = pmd.getParameterCount();
			for(int i=1;i<count;i++){
				ps.setObject(i, params[i-1]);
			}
			rs=ps.executeQuery();
			while (rs.next()) {
				System.out.print(rs.getObject(1)+" ");
				System.out.print(rs.getObject(2)+" ");
				System.out.print(rs.getObject(3)+" ");
				System.out.println();
			}
		}
		finally{
			JdbcUtils.free(rs, ps, conn);
		}
	}
}


 

 

posted @ 2014-01-15 23:51  MrMrCash  阅读(415)  评论(0编辑  收藏  举报