簡體   English   中英

如何從Java中的HashMap獲取特定值

[英]How can I get a specific value from a HashMap in Java

我正在嘗試從HashMap獲取值ID,但我沒有到達那里,這是代碼

try {
    Connection lig = DriverManager.getConnection(dbURL,"root", "");
    Statement inst = lig.createStatement();
    String nome = txtNquest.getText();
    int id = questionarios3.get(nome);
    Connection lig3;
    try {
        lig3 = DriverManager.getConnection(dbURL, "root", "");
        PreparedStatement inst2 = lig3.prepareStatement("SELECT pergunta,id FROM perguntas WHERE Questionarios_id=?");
                        inst2.setInt(1, id);
        ResultSet res = inst2.executeQuery();

        while (res.next()) {
            perguntasmap2.put(res.getString("pergunta"),
            res.getInt("id"));
        }
        lig3.close();
    } catch (SQLException e2) {
        JOptionPane.showMessageDialog(frame,"Impossível ligar à base de dados\n"
                                            + e2.getLocalizedMessage());
    }

    inst.executeUpdate("DELETE FROM respostas WHERE idPerguntas="+ id2);

我正在嘗試使用HashMap的ID'perguntasmap2'並將該ID用於DELETE中的id2,更具體

perguntasmap2.put(res.getString("pergunta"),res.getInt("id"));

使用此ID並輸入此值(id2)

inst.executeUpdate("DELETE FROM respostas WHERE idPerguntas="+ id2);

我想從特定的問題刪除所有答案='respostas'='pergunta',我還沒有嘗試任何,因為我真的不知道如何做到這一點,在我的數據庫中我得到了更多的值'perguntas '和'respostas'都是用id組織來幫忙的

好吧,有些問題我有疑問:

perguntasmap2.put(res.getString("pergunta"),res.getInt("id"));

為什么要將id放在與地圖中的值相關的字段中? 是不是會更好地投入Key領域? 喜歡

perguntasmap2.put(res.getInt("id"), res.getString("pergunta"));

inst.executeUpdate("DELETE FROM respostas WHERE idPerguntas="
                                    + id2);

您嘗試使用idPerguntas =刪除respostas,但是您將擁有多個pergunta的id,也許您必須WHERE idPerguntas in (id)使用WHERE idPerguntas in (id)

如果你想從pergunta的所有id刪除所有的respostas,你把pergunta的id放在hashmap的關鍵字段中,就像我上面所示,你可以這樣做:

String ids = new org.apache.commons.lang.StringUtils().join(map.keySet(), ",");

你不需要apache commons,你可以通過一個簡單的for循環來完成。

"DELETE FROM respostas WHERE idPerguntas in (" + ids + ")");

Se tiver maisalgumadúvida,estamos ai! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM