com.spun.util.database.ResultSetWriter Maven / Gradle / Ivy
package com.spun.util.database;
import com.spun.util.ObjectUtils;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ResultSetWriter
{
public static String toString(ResultSet rs)
{
List results = extractResults(rs);
List metaData = extractMetaData(rs);
StringBuffer sb = new StringBuffer();
sb.append(metaData.toString() + "\n");
for (String[] strings : results)
{
sb.append(Arrays.toString(strings) + "\n");
}
return sb.toString();
}
public static List extractResults(ResultSet rs)
{
try
{
int columns = rs.getMetaData().getColumnCount();
ArrayList found = new ArrayList();
while (rs.next())
{
String[] rowData = new String[columns];
for (int i = 1; i <= columns; i++)
{
rowData[i - 1] = rs.getString(i);
}
found.add(rowData);
}
return found;
}
catch (Exception e)
{
throw ObjectUtils.throwAsError(e);
}
}
public static List extractMetaData(ResultSet rs)
{
try
{
ResultSetMetaData meta = rs.getMetaData();
ArrayList titles = new ArrayList(meta.getColumnCount());
for (int i = 1; i <= meta.getColumnCount(); i++)
{
titles.add(meta.getColumnName(i));
}
return titles;
}
catch (Exception e)
{
throw ObjectUtils.throwAsError(e);
}
}
}