Problem with TIMER insertion in Mysql table using JDBC

Asked

Viewed 57 times

0

Personal talk!

I have the following problem and I am looking for the best possible solution. The following code when running a time is saved in the tAtual (current time) string and sent to the database for the time column. This current time is updated every moment, so the next time value will overwrite the current value. To correct this I created a new column, called ttotal (total time), where the idea is that it sum up the current time with the previous time. For this I need to make a query of the time and add with the string tAtual and so do the update of the ttotal column of the database. But how do I add two Time Strings? or two Timers? There is a better way to sum these values that do a query and update at the same time?

 String tAtual = String.format("%02d:%02d:%02d", horas, minutos, segundos); //Esse é o tempo atual
    String sql = "UPDATE vagas SET tempo = (?) WHERE nomeID = (?)";

    try (PreparedStatement ps = Conecta.conn.prepareStatement(sql)) {
        ps.setString(1, tAtual);
        ps.setString(2, temp.getNome());
        ps.executeUpdate();
    }
    //System.out.println(temp.getNome() + " levou " + tAtual);//salva e mostra o tempo atual

    String sql2 = ("SELECT tempo FROM vagas WHERE nomeID =(?)");

    Time tempo = null;
    try (PreparedStatement ps2 = Conecta.conn.prepareStatement(sql2)) {
        ps2.setString(1, temp.getNome());
        ResultSet rs = ps2.executeQuery();
        while (rs.next()) {
            tempo = rs.getTime("tempo");//fiz a query do tempo 
        }
    }

    //tTotal é a soma do tempo que já está no banco de dados com o tAtual    
    String sql3 = ("UPDATE vagas SET Ttotal = (?) WHERE nomeID = (?)");
    //String tTotal = tAtual + tempo; //Problema maior aqui
    try (PreparedStatement ps3 = Conecta.conn.prepareStatement(sql3)) {
        ps3.setString(1, tTotal);
        ps3.setString(2, temp.getNome());
        ps3.executeUpdate();
    }

1 answer

1


One option is to use the function ADDTIME mysql:

UPDATE vagas set tempo = :tempo, ttotal = ADDTIME(ttotal, :tempo)
WHERE nomeID = :nomeID

Notice that we are using named Parameters, that should be set this way:

try (PreparedStatement ps = Conecta.conn.prepareStatement(sql)) {
    ps.setString("tempo", tAtual);
    ps.setString("nomeID", temp.getNome());
    ps.executeUpdate();
}
  • Excellent, I only needed to change the "time" and the "IName" for values of type int (which is the acceptable as setString parameter) and in String I made use of (?). Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.