[英]How to create a list using PreparedStatement?
我有以下代碼:
- - - -類 - - - - - -
private class SystemHealthAlert implements Work {
List<MonitorAlertInstance> systemHealthAlertList;
private String queryString;
// private java.util.Date startDate;
// private java.util.Date endDate;
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(queryString);
int index = 1;
ResultSet rs = ps.executeQuery();
int columnCount = rs.getMetaData().getColumnCount();
while(rs.next())
{
//String[] row = new String[columnCount];
//results.set(index, element);
//for (int i=0; i <columnCount ; i++)
// {
// row[i] = rs.getString(i + 1);
// }
systemHealthAlertList.add(row);
}
rs.close();
ps.close();
}
}
- - - - -方法 - - - - - -
public List<MonitorAlertInstance> getSystemHealthAlert(Long selectedSensorId) {
List<MonitorAlertInstance> systemHealthAlertList;
try {
// Add SELECT with a nested select to get the 1st row
String queryString = "select min(MONITOR_ALERT_INSTANCE_ID) as MONITOR_ALERT_INSTANCE_ID, description" +
" from ems.monitor_alert_instance " +
" where description in (select description from monitor_alert_instance" +
" where co_mod_asset_id = " + selectedSensorId +
" )" +
" group by description";
SystemHealthAlert work = new SystemHealthAlert();
// work.coModAssetId = coModAssetId;
work.queryString = queryString;
getSession().doWork(work);
systemHealthAlertList = work.systemHealthAlertList;
} catch (RuntimeException re) {
// log.error("getMostRecentObservationId() failed", re);
throw re;
}
//log.info("End");
return systemHealthAlertList;
}
我的查詢從數據庫返回三行。 如何從將具有查詢的所有三行的類中返回systemHealthAlertList。
在方法execute
,應使用List<MonitorAlertInstance> systemHealthAlertList
的實例填充List<MonitorAlertInstance> systemHealthAlertList
MonitorAlertInstance
。 在while
循環內創建MonitorAlertInstance
的新實例, MonitorAlertInstance
在其中檢索數據:
//You don't need this line, remove it
//int columnCount = rs.getMetaData().getColumnCount();
while(rs.next()) {
//create a new instance of MonitorAlertInstance per ResultSet row
MonitorAlertInstance monitor = new MonitorAlertInstance();
//set the fields from the ResultSet in your MonitorAlertInstance fields
//since I don't know the fields of this class, I would use field1 and field2 as examples
monitor.setField1(rs.getInt(1));
monitor.setField2(rs.getString(2));
//and on...
systemHealthAlertList.add(monitor);
}
List<MonitorAlertInstance> systemHealthAlertList
問題外,還應在使用它之前初始化List<MonitorAlertInstance> systemHealthAlertList
變量:
systemHealthAlertList = new ArrayList<MonitorAlertInstance>();
while(rs.next()) {
//content from previous code...
}
定義一個類/ bean來保存給定行中的數據。 遍歷行,並為每行創建一個該類的實例。 將這些實例添加到某些列表。 返回這3個實例的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.