Java中直接执行sql语句,返回List集合
public static List<Map<String, Object>> getResultToList(String sql, Object... params) {
PreparedStatement ps = null;
Connection conn = getConnection();
ResultSet rs = null;
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
if (null == sql || "".equals(sql)) {
return new ArrayList<Map<String, Object>>();
}
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<String, Object> record = null;
if (count > 0) {
while (rs.next()) {
record = new HashMap<String, Object>();
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();
}
}
}
}
执行语句
<pre name="code" class="java">getResultToList("select * from user where us_name where us_name=?","田")
<pre name="code" class="java">getResultToList("select * from user where us_name where us_name='田'")
两个效果是一样的