Problems with the JDBC connection

Asked

Viewed 106 times

2

Good morning, my dear. I’m having trouble with jdbc. The connection to the bank is made but, does not bring anything with select. The eclipse console reported me some problems, such as: The proto-buf-java lib was missing, so I put the dependency on Maven. I’m using mysql BD, and I put the newest version of the connector. I put the getRow method, to indicate the number of lines that he’s picking up and redeveloped zero. First I’ll put connection class.

protected Connection getConnection() throws Exception,SQLException{
    String driverName = "com.mysql.cj.jdbc.Driver";
        try {
            Class.forName(driverName);
        }catch(ClassNotFoundException cne) {
            System.out.println("Driver não encontrado");
        }
        try{                        
                    //Properties props = getProp();

                       String url = "jdbc:mysql://500.500.500.100:3306/sgbdmysql";
                       String usuario = "user";
                       String senha = "password";
                     //Conecta usando a URL, usuario e senha
                    Connection conn = DriverManager.getConnection(url, usuario, senha);
                    System.out.println(conn);
                    return conn;
        }
        catch(SQLException e){
            System.out.println(e);
            throw e;
        }



    }
Classse DAO

public Date getDataOperacao()throws Exception,SQLException{
        Connection conn = null;
        PreparedStatement stmt = null;
        Date dta = null;
        try {
            conn = getConnection();
            //Teste Mau - sucedido
            String str = "SELECT dataoperacao FROM cimentacao_grafico WHERE well_name LIKE 'well3%' \n" + 
                    " ORDER BY idgrafico DESC LIMIT 1";
            //stmt = conn.prepareStatement("SELECT dataoperacao FROM cimentacao_grafico WHERE well_name LIKE 'well3%' \n" + 
            //      " ORDER BY idgrafico DESC LIMIT 1");
            stmt = conn.prepareStatement("SELECT * FROM cimentacao_hkloadcritico");
            ResultSet rs = stmt.executeQuery();
            System.out.println(rs.getRow());
            if (rs.getRow() == 0) {
                dta = new Date();
            } else {
                dta = rs.getDate("dataoperacao");
            }

        }finally {
            if(stmt != null) {
                stmt.close();
            }
            if(conn != null) {
                conn.close();
            }
        }
        return dta;
    }
  • Look at the properties for me isClosed and isValid of connection.

  • The table cimentacao_hkloadcritico has records?

  • Yes, there are four records to be exact.

  • You do not edit the title to mark as "solved". You accept the answer that actually solved your problem. In the absence of such a response, create your own response and accept it

  • And how do you accept the answer I was given? I looked for somewhere to do this and I couldn’t find it. It’s been a long time since I used stackoverflow.

1 answer

1


I believe you’re confusing the purpose of the method getRow(), removing the section of documentation:

Retrieves the current row number. The first row is number 1, the second number 2, and so on. 

Recalling that the starting position of ResultSet is always 0 (zero), if you simply refer, and call the method getRow() he will return to you 0 (zero).

If the logic you’re looking for is to see if there have been any results, and if there hasn’t been a return to the current date, maybe what you want to do is the following:

if( rs.next() ) { // Verifica se existe um próximo registro no ResultSet
    dta = rs.getDate("dataoperacao");
} else {
    dta = new Date();
}

The method rs.next() will walk in the ResultSet, and if there is a record will return true.

Should you call the getRow() after the rs.next(), you will receive as a result 1 (a), since you’re on the first line of ResultSet.

Applying the methods ResultSet.get...() will then return you the value of the line you are currently on.

Recalling that the if( rs.next() ) will only check if there is a next line as a result, if you want to iterate over several lines I suggest using the while( rs.next() ), but adjusting your condition when there are no results.


I forgot to mention, in case you want to know the total amount of records in your ResultSet, then you would continue to use the getRow() but as follows:

if( rs.last() ) {
    System.out.println("Total de linhas: " + rs.getRow());
    rs.beforeFirst(); // Retorna a posição do ResultSet para posição original (0)
}
  • Actually, I was wrong about the use of getRow. So much so that, I discovered that he masked what I had done previously, maybe I had forgotten. But, by conscience disembowelment, I put the code that you suggested and it worked. Very worked even by the help.

  • Don’t forget to mark the answer as correct :)

Browser other questions tagged

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