Problem with inserting TIMER into MySQL table using JDBC

0

Speak up!

I have the following problem and I'm looking for the best possible solution. The following code when running a time is saved in the CurrentTime (current time) and sent to the database for the time column. This current time is updated at all times, 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 to make the sum of the current time with the previous time. For this I need to do a time query and add with the string tAtual and thus do the Update of the tTotal column of the database. But how do I add two Strings of time? or two Timers? Is there a better way to add these values to 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();
    }
    
asked by anonymous 15.08.2016 / 01:21

1 answer

1

One option is to use the function ADDTIME of MySQL:

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

Notice that we are using named parameters , which should be set like this:

try (PreparedStatement ps = Conecta.conn.prepareStatement(sql)) {
    ps.setString("tempo", tAtual);
    ps.setString("nomeID", temp.getNome());
    ps.executeUpdate();
}
    
15.08.2016 / 13:19