【发布时间】:2018-06-23 16:04:21
【问题描述】:
我有一个方法,它接受数据库连接、查询和参数并将该查询解析为结果集对象。这很好,但问题是要从结果集中获取每个值,我必须为要提取的每一行数据编写一行代码,然后将其保存在 JSON 容器中。有没有办法系统地执行此操作,以便我可以自动解析数据类型并根据从结果集中获取的键创建 JSON 对象,而无需手动指定键?
public static JSONArray q2rs2j(Connection connection, String query, List<String> params) throws Exception {
JSONArray tContainer = new JSONArray();
PreparedStatement pStatement = connection.prepareStatement(query);
int pit = 1;
if(params != null) {
for (String param : params) {
try {
double paramAsDouble = Double.parseDouble(param);
try {
int paramAsInt = Integer.parseInt(param);
pStatement.setInt(pit, paramAsInt);
} catch (NumberFormatException e) {
pStatement.setDouble(pit, paramAsDouble);
}
} catch (NumberFormatException e) {
pStatement.setString(pit, param);
}
pit++;
}
}
ResultSet resultSet = pStatement.executeQuery();
try {
while (resultSet.next()) {
// Iterate through KEYS in the resultSet.next() row
while (hasKey) {
// Store key Name and key Value in variables - todo: determine data type via try parsing as Int, double, etc
String thisKeyName = (nextKeyName);
String thisKeyValue = (nextKeyValue);
JSONObject tObject = new JSONObject();
tObject
.put(nextKeyName, nextKeyValue);
}
tContainer.put(tObject);
}
resultSet.close();
} catch (Exception e) { e.printStackTrace(); }
return tContainer;
}
【问题讨论】: