是用JDBC从数据库中获取数据并以java对象返回

/**
	 * 
	 * @param c
	 *            for example Person.class
	 * @param primaryKeys
	 *            primaryKeys为主键,参数顺序和表中保持一致 如果id, name 为主键 类名为Person 则 getEntity(Person.class,1,"name")
	 * @return
	 */
	public static Object getEntity(Class c, Object... primaryKeys) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		DatabaseMetaData dmd = null;
		Object obj = null;// 要返回的对象
		String tableName = c.getSimpleName().toLowerCase();// person 表的名字
		List primaryKeyNameList = new ArrayList();
		Field[] fields = c.getFields();// 获取所有的属性
		StringBuilder sql = new StringBuilder("select * from " + tableName
				+ " where ");
		try {
			obj = c.newInstance();
			dmd = getConnection().getMetaData();
			rs = dmd.getPrimaryKeys(null, null, tableName);
			while (rs.next()) {
				sql.append(rs.getObject(4) + "=?");
				sql.append(" and ");
				primaryKeyNameList.add(rs.getObject(4));// 将从表中获取的 主键字段存到 list中, 主键位于表中第几列=rs.getString(5)
			}
			sql.delete(sql.length() - 4, sql.length());
			ps = (PreparedStatement) getConnection().prepareStatement(
					sql.toString());
			for (int l = 0; l < primaryKeyNameList.size(); l++) {
				ps.setObject(l + 1, primaryKeys[l]);
			}
			rs = ps.executeQuery();
			System.out.println(ps.toString().split(":")[1]);
			if (rs.next()) {
				for (int k = 0; k < fields.length; k++) {
					fields[k].set(obj, rs.getObject(k + 1));
				}
			}
			rs.close();
			ps.close();
			rs=null;
			ps=null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
		return obj;
	}

你可能感兴趣的:(Java)