I am facing what I think is a fairly common problem for which there might be a standard solution.
I use an inner class to represent a row in a database table.
The column names are represented with an enumeration.
The column values, themselves, are stored as instance values.
I perceive the problem to be that I need someway to associate each item in the enum in
Row with an instance variable in
Row .
public final class TblDictionary {
Set<Row> dbTbl = new HashSet<Row>();
// ......
public int loadIntoDb(Connection conn) throws Exception {
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO dictionary(");
for(Row.ColName c : Row.ColName.values()) sql.append(" " + c + ",");
sql.deleteCharAt(sql.length() - 1);
sql.append(") VALUES(");
for(Row.ColName c : Row.ColName.values()) sql.append(" ?,");
sql.deleteCharAt(sql.length() - 1);
sql.append(")");
PreparedStatement prpStmt = conn.prepareStatement(sql.toString());
for(Row r : dbTbl) {
for(Row.ColName c : Row.ColName.values()) prpStmtInsert(prpStmt, r, c);
prpStmt.executeUpdate();
}
}
static void prpStmtInsert(PreparedStatement ps, Row r, Row.ColName c) throws Exception {
Object obj = r.getObj(c);
if(String.class.isInstance(obj)) { ps.setString(c.ordinal() + 1, obj.toString()); return; }
if(Integer.class.isInstance(obj)) { ps.setInt(c.ordinal() + 1, ((Integer) obj).intValue()); return; }
}
static class Row {
public enum ColName {
WORD, DEF, PAGENMB
}
final public int pagenmb;
final public String word, def;
Row(String word, String def, int pagenmb) {
this.word = word; this.def = def; this.pagenmb = pagenmb;
}
private Object getObj(ColName col) {
if(col == ColName.WORD) return word;
if(col == ColName.DEF) return def;
if(col == ColName.PAGENMB) return Integer.valueOf(pagenmb);
return null;
}
}
}
Because the classes represented by the enum are not all of the same type, I can only cast out of "getObj(ColName col);" to Object. Then, I must rely on "*.class.isInstance(x)" or reflection to deal with the returned object.
" loadIntoDb(Connection conn)" is a flexible method. I cut/paste it into all my classes and needs almost no changes to make it work. But I have that problem of how to extract the value of a column from an instance of
Row by specifying the column name using the ColName enumeration.
Edited by: triym on Aug 8, 2011 5:43 PM