简体   繁体   中英

How can I get a specific value from a HashMap in Java

I'm trying to get the value ID from the HashMap but I'm not getting there, this is the code

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);

I'm trying to use the ID of HashMap 'perguntasmap2' and use that ID for the id2 in the DELETE , more specific

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

using this ID and put in this value(id2)

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

I want to delete all answers='respostas' from that specific question='pergunta',I din't try anyting yet ,because I don't really know a way to do it,in my data base I got more values 'perguntas' and 'respostas' both organized with id's to help

Ok, some points that I'm in doubt:

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

Why you put the id in field that pertences to the value in a map? Is will not better put in Key field? like

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

And

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

You try to delete respostas using idPerguntas=, but you will have more than one id of pergunta, maybe you must use WHERE idPerguntas in (id) ?

if you want delete all respostas from all id's of pergunta, and you put the id of pergunta in key field of hashmap, like I showed above, you can do:

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

You don't need apache commons, you could do this with a simple for loop.

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

Se tiver mais alguma dúvida, estamos ai! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM