我正在重述我的问题,因为显然有些人无意中被冒犯了(我是一个Java新手):(
我正在连接到DB2 db - ResultSet包含表V_LVCS中的前10行。
我希望实现这一目标!
while (rs.next())
{ keys[i] = new V_LVCS();
keys[i] = this_Row_Object;
}
我在一系列V_LVCS对象之后。目前我正在将每个数据行转换为V_LVCS对象,如下所示,但我认为有更好的方法可以做到这一点。
public class V_LVCS {
public String SERIAL;
public String TRANSFORMERID;
public String LVT;
public V_LVCS() {
}
public V_LVCS(String Serial, String Transformerid, String lvt) {
this.SERIAL = Serial;
this.TRANSFORMERID = Transformerid;
this.LVT = lvt;
}
public V_LVCS[] getAllV_LVC() {
try {
Connection conn = getAMMDBConnection();
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs;
rs = stmt.executeQuery("SELECT * FROM V_LVC FETCH FIRST 10 ROWS ONLY");
rs.last();
int numRows = rs.getRow();
V_LVCS[] keys = new V_LVCS[numRows];
rs.beforeFirst();
int i = 0;
while (rs.next()) {
keys[i] = new V_LVCS();
keys[i].SERIAL = (rs.getString("SERIAL") == null) ? "" : rs.getString("SERIAL");
keys[i].LVT = (rs.getString("LVT") == null) ? "" : rs.getString("LVT");
keys[i].TRANSFORMERID = (rs.getString("TRANSFORMERID") == null) ? "" : rs.getString("TRANSFORMERID");
++i;
}
conn.close();
System.out.println("stop!");
return keys;
} catch (Exception e) {
System.err.println("Got an exception! ");
// System.err.println(e.printStackTrace());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
return null;
}
}
}
我真的很感激你的想法! (希望在用-ve分数受到惩罚之前花几个小时!)
答案 0 :(得分:5)
您只需要更改循环以调用构造函数,而不是尝试分配给字段:
while ( rs.next() ) {
String serial = ( rs.getString("SERIAL") == null)?"":rs.getString("SERIAL") ;
String lvt = ( rs.getString("LVT") == null)?"":rs.getString("LVT");
String id = ( rs.getString("TRANSFORMERID") == null)?"":rs.getString("TRANSFORMERID") ;
keys[i] = new V_LVCS(serial, id, lvt);
++i;
}
特别注意,这一行:
V_LVCS [] keys = new V_LVCS[numRows];
创建一个对V_LVCS
,的引用数组,所有引用都是 null
。在取消引用该元素之前,您需要为每个元素指定一些内容。