我目前正在研究Java项目(在NetBeans上),我正在努力解决问题。
事实上,我有一个jTable
,其中包含几个元素,第二列中的元素有jCheckBox
,我想进行查询以添加所选元素(由{选中)当然{1}}在表格中。
我可以获取要添加的数据,但我的查询只能运行一次。我已经检查了我的循环,但我不知道问题的来源。
我让你看到代码:
jCheckBox
提前感谢您的帮助。
这是我的陈述
try {
// Getting id of the selected value in the jComboBox
String idParcours = oParcoursDAO.findIdParcours(jComboBoxParcours.getSelectedItem().toString());
int id = Integer.parseInt(idParcours);
// for each value in the jTable
for(int i=0; i <jTable2.getRowCount(); i++){
boolean isChecked = (Boolean)jTable2.getValueAt(i, 1);
String nomPoi = (String)jTable2.getValueAt(i, 0);
// if the value is selected
if(isChecked){
String IDPoi = oParcoursDAO.findIdPoi(nomPoi);
int idpoi = Integer.parseInt(IDPoi);
System.out.println("idpoi "+idpoi); // It works I saw as idpoi as I have choose
System.out.println("id "+id) // It works too
oParcoursDAO.addPoi(idpoi,id); // it works only once
}
}
}catch (SQLException ex) {
Logger.getLogger(ModificationParcoursJInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
答案 0 :(得分:2)
为什么每行都运行一个查询?您可以使用批处理查询在单个SQL中执行所有这些操作。它将要求您更改代码,但它会提高效率:
public void addPoi(Map<integer,Integer> poiMap) throws SQLException{
String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
PreparedStatement preparedStatement = conn.prepareStatement(query);
for(Integer idPoi:poiMap.keySet()) {
preparedStatement.setInt(1,idPoi);
preparedStatement.setInt(2,poiMap.get(idPoi));
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
preparedStatement.close();
}
当然必须相应地更改原始方法。