Java中直接执行sql语句,返回List集合

Java中直接执行sql语句,返回List集合

public static List> getResultToList(String sql, Object... params) {

		PreparedStatement ps = null;
		Connection conn = getConnection();
		ResultSet rs = null;
		List> rows = new ArrayList>();
		if (null == sql || "".equals(sql)) {
			return new ArrayList>();
		}
		try {
			ps = conn.prepareStatement(sql);
			if (null != params && params.length > 0) {
				for (int i = 0, len = params.length; i < len; i++) {
					Object arg = params[i];
					ps.setObject(i + 1, arg);
				}
			}
			rs = ps.executeQuery();
			if (null != rs) {
				ResultSetMetaData rsm = rs.getMetaData();
				int count = rsm.getColumnCount();
				Map record = null;
				if (count > 0) {
					while (rs.next()) {
						record = new HashMap();
						for (int j = 0; j < count; j++) {
							Object obj = rs.getObject(j + 1);
							String columnName = rsm.getColumnName(j + 1);
							record.put(columnName.toLowerCase(),(obj == null) ? "" : obj);
						}
						rows.add(record);
					}
				}

			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			release(rs, ps, conn);
		}

		return rows;
	}

//关闭
public static void release(Object...obj){
		if(null!=obj){
			for(Object o:obj){
				try {
					if (o instanceof ResultSet) {
						((ResultSet) o).close();
					} else if (o instanceof Statement) {
						((Statement) o).close();
					} else if (o instanceof Connection) {
						((Connection) o).close();
					}else if (o instanceof PreparedStatement) {
						((PreparedStatement) o).close();
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
执行语句
getResultToList("select * from user where us_name where us_name=?","田")
getResultToList("select * from user where us_name where us_name='田'")
两个效果是一样的

 
  
 
  

你可能感兴趣的:(java)