【问题标题】:Query in a loop which is executed only once Java在循环中查询,只执行一次 Java
【发布时间】:2014-03-06 17:43:01
【问题描述】:

我目前正在处理一个 Java 项目(在 NetBeans 上),我正在努力解决一个问题。

事实上,我有一个jTable,其中包含几个元素,哪个元素在第二列中有一个jCheckBox,我想进行查询以添加所选元素(当然是由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);
}

提前感谢您的帮助。

这是我的声明

public void addPoi(int idPoi,int idParcours) throws SQLException{

    String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
    PreparedStatement preparedStatement = conn.prepareStatement(query);
    preparedStatement.setInt(1,idPoi);
    preparedStatement.setInt(2,idParcours);  
    preparedStatement.executeUpdate();
    preparedStatement.close();
}

【问题讨论】:

  • 我看到您的代码没有错误,所以尝试调试您的代码并在每行后添加打印语句以检查问题出在哪里
  • 我已经尝试过了,当我打印查询时,它被打印了很多次,所以我真的不明白为什么我的数据库中只有一个 add ..
  • 所以我猜你的数据库有问题,所以你能发布你的数据库语句吗?
  • 我已经编辑了我的帖子@Alya'aGamal
  • 难道你不能在 TB_POI_PARCOURS 表中将 id_poi 标记为 UNIQUE 吗?

标签: java sql swing for-loop jdbc


【解决方案1】:

为什么每行运行一个查询?您可以使用批处理查询在单个 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();
}

当然,原来的方法也要相应地改变。

【讨论】:

  • 感谢您的回复。我不知道批量查询!我是初学者,对Map不熟悉,能告诉我怎么用吗?
  • 转换你原来的方法,将 poiId 和 parcoursId 保存为 Hashmap,然后调用 addPoi() 一次,与 map。给出了 getPoi() 的代码。
猜你喜欢
  • 2014-02-27
  • 1970-01-01
  • 2023-04-02
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多