Last active
October 16, 2024 02:12
-
-
Save marlonlom/5310a52bf09a46c345d9 to your computer and use it in GitHub Desktop.
A simple Java Utility for converting java.sql.ResultSet object and contents into some Output formats (JSON, XML) .
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.ResultSet; | |
import java.sql.ResultSetMetaData; | |
import org.json.JSONArray; | |
import org.json.JSONObject; | |
/** | |
* Utility for converting ResultSets into some Output formats | |
* | |
* @author marlonlom | |
*/ | |
public class ResultSetParserUtil { | |
/** | |
* Convert a result set into a JSON Array | |
* | |
* @param resultSet | |
* @return a JSONArray | |
* @throws Exception | |
* if something happens | |
*/ | |
public static JSONArray convertToJSON(ResultSet resultSet) throws Exception { | |
JSONArray jsonArray = new JSONArray(); | |
if (resultSet != null) { | |
while (resultSet.next()) { | |
ResultSetMetaData metaData = resultSet.getMetaData(); | |
int total_rows = metaData.getColumnCount(); | |
JSONObject obj = new JSONObject(); | |
for (int i = 0; i < total_rows; i++) { | |
String rKey = metaData.getColumnLabel(i + 1).toLowerCase(); | |
Object rVal = resultSet.getObject(i + 1); | |
obj.put(rKey, rVal); | |
} | |
jsonArray.put(obj); | |
} | |
} | |
return jsonArray; | |
} | |
/** | |
* Convert a result set into a XML List | |
* | |
* @param resultSet | |
* @return a XML String with list elements | |
* @throws Exception | |
* if something happens | |
*/ | |
public static String convertToXML(ResultSet resultSet) throws Exception { | |
StringBuilder xmlArray = new StringBuilder("<results>"); | |
if (resultSet != null) { | |
while (resultSet.next()) { | |
ResultSetMetaData rstMetaData = resultSet.getMetaData(); | |
int total_rows = rstMetaData.getColumnCount(); | |
xmlArray.append("<result "); | |
for (int i = 0; i < total_rows; i++) { | |
String rKey = rstMetaData.getColumnLabel(i + 1).toLowerCase(); | |
Object rVal = resultSet.getObject(i + 1); | |
xmlArray.append(" "); | |
xmlArray.append(rKey); | |
xmlArray.append("='"); | |
xmlArray.append(rVal); | |
xmlArray.append("'"); | |
} | |
xmlArray.append(" />"); | |
} | |
xmlArray.append("</results>"); | |
} | |
return xmlArray.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment