您的位置:首页 > 数据库

使用预处理PreparedStatement执行Sql语句

2014-11-06 15:26 225 查看
/**
* 使用预处理的方式执行Sql
* @param sql Sql语句
* @param obj 变量值数组
* @return 查询结果
* @throws SQLException
*/
public List<Map<String, Object>> query(String sql, Object[] obj) throws SQLException
{
List<Map<String, Object>> ret = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
log.debug("start sql="+sql);
ps = conn.prepareStatement(sql);
if(obj != null && obj.length > 0){
for (int i = 0, len = obj.length; i < len; i++) {
ps.setObject(i + 1, obj[i]);
log.debug("parameterValue: " + obj[i]);
}
}
rs = ps.executeQuery();
ResultSetMetaData rmd = rs.getMetaData();
ret = new ArrayList<Map<String,Object>>();
while (rs.next()) {
Map<String, Object> rowMap = new LinkedHashMap<String, Object>();
for (int i = 1, count = rmd.getColumnCount() + 1; i < count; i++) {
rowMap.put(rmd.getColumnName(i), rs.getObject(i));
}
ret.add(rowMap);
}
} catch (SQLException e) {
log.debug("执行sql语句失败,sql: " + sql + "," + e.getMessage());
throw e;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: