resultset 转换成对象
resultset 转换成对象
public JSONArray executeSQL(String sql) {
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
JSONArray jsonArray = new JSONArray();
try {
con = DbUtil.getConnection();
con.setAutoCommit(false);
pstm = con.prepareStatement(sql);
rs = pstm.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int colCnt = metaData.getColumnCount();
while (rs.next()) {
JSONObject jsonObject = new JSONObject();
for(int i=1;i<=colCnt;i++){
jsonObject.put(metaData.getColumnName(i),rs.getObject(i));
}
jsonArray.add(jsonObject);
}
con.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtil.close(con, pstm, rs);
}
return jsonArray;
}
resultset 更新、插入
另外 con.prepareStatement 如果这样设置了可以查询的时候进行更新,适用少量更新的情况
pstm = con.prepareStatement(behaviorSQL.getSql(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
并且查询的时候也要将需要更新插入的字段查询出来,所以下面的 DEPT_NAME,SERIAL_NO字段都得查询出来才能更新插入。
例如:
while (rs.next()) {
rs.updateString("DEPT_NAME", jsonObject1.optString("name"));
rs.updateRow();
}
新增要加上 moveToInsertRow
while (rs.next()) {
rs.moveToInsertRow();
rs.updateString("SERIAL_NO", PubSupport.getSeqId("nullseq").toString());
rs.updateString("DEPT_NAME", jsonArray.getJSONObject(i).optString("name"));
rs.insertRow();
}