Is it possible to retrieve entire row without calling getInt(..) getString(..) for every column?
I have multiple threads, each tread needs to write the result to some thread safe collection.
I want to be able to write the rows directly to this collection, and after that parse the members of this collection and retrieve the values based on column types.
You can build a class like this one, which maps sql data types with java data types:
class Row
{
public Map <Object,Class> row;
public static Map <String, Class> TYPE;
static
{
TYPE = new HashMap<String, Class>();
TYPE.put("INTEGER", Integer.class);
TYPE.put("TINYINT", Byte.class);
TYPE.put("SMALLINT", Short.class);
TYPE.put("BIGINT", Long.class);
TYPE.put("REAL", Float.class);
TYPE.put("FLOAT", Double.class);
TYPE.put("DOUBLE", Double.class);
TYPE.put("DECIMAL", BigDecimal.class);
TYPE.put("NUMERIC", BigDecimal.class);
TYPE.put("BOOLEAN", Boolean.class);
TYPE.put("CHAR", String.class);
TYPE.put("VARCHAR", String.class);
TYPE.put("LONGVARCHAR", String.class);
TYPE.put("DATE", Date.class);
TYPE.put("TIME", Time.class);
TYPE.put("TIMESTAMP", Timestamp.class);
// ...
}
public Row ()
{
row = new HashMap<Object,Class>();
}
public void add<t> (t data)
{
row.put(data, data.getClass());
}
public void add (Object data, String sqlType)
{
add((Row.TYPE.get(sqlType)) data);
}
public static void formTable (ResultSet rs, ArrayList<Row> table)
{
if (rs == null) return;
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
while (rs.next())
{
row = new Row ();
for(int i = 1; i <= NumOfCol; i++)
{
row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
}
table.add(row);
}
}
}
Which you can use it like this:
List<Row> table = new ArrayList<Row>();
Row row = null;
ResultSet rs = st.executeQuery("SELECT * FROM table_name");
Row.formTable(rs, table);
Then you can retrieve fields and cast them to their respective data types:
for (Row row : table)
{
for (Object data : row.row.getKeySet())
{
System.out.print(" > " + ((row.row.get(data) data));
}
System.out.println();
}