2016-02-20 3 views
-1

У меня возникла проблема с возвратом строки из соединения с базой данных. В нем говорится, что return_statement «возможно, не был инициализирован», конечно, но если я поставлю точку возврата внутри try, он говорит «нет возврата в объект». Я немного нуб, пожалуйста, не обессудьте:/Возврат строки из результатов

import java.sql.*; 

public class DbConnector { 

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
    static final String DB_ADDRESS = "jdbc:mysql://localhost:8889/java_prog"; 

    String query; 

    static final String USER = "root"; 
    static final String PASS = "root"; 





    public static String dbAsker (String query){ 
    Connection conn = null; 
    Statement stmt = null; 
    String return_statement; 

    try{ 
     //STEP 2: Register JDBC driver 
     Class.forName("com.mysql.jdbc.Driver"); 

     //STEP 3: Open a connection 
     System.out.println("Connecting to database..."); 
     conn = DriverManager.getConnection(DB_ADDRESS,USER,PASS); 

     //STEP 4: Execute a query 

     ResultSet rs = stmt.executeQuery(query); 



    return_statement = rs.toString(); 

     //STEP 6: Clean-up environment 
     rs.close(); 
     stmt.close(); 
     conn.close(); 

    }catch(SQLException se){ 
     //Handle errors for JDBC 
     se.printStackTrace(); 
    }catch(Exception e){ 
     //Handle errors for Class.forName 
     e.printStackTrace(); 
    }finally{ 
     //finally block used to close resources 
     try{ 
     if(stmt!=null) 
      stmt.close(); 
     }catch(SQLException se2){ 
     }// nothing we can do 
     try{ 
     if(conn!=null) 
      conn.close(); 
     }catch(SQLException se){ 
     se.printStackTrace(); 
     }//end finally try 
    }//end try 
    System.out.println("Goodbye!"); 

    return return_statement; 



    } 
} 
+0

Попробуйте эту строку return_statement = ""; – Abdelhak

+0

'Statement stmt' не инициализирован' stmt = conn .createStatement(); 'missing –

+0

Возможный дубликат http://stackoverflow.com/questions/14484550/java-variables-not-initialized-error – Rehman

ответ

0

Использование String return_statement = null; или String return_statement = ""; вместо String return_statement;. Если исключение произошло, return_statement не имеет никакого значения при использовании взамен, это невозможно в Java.

Смежные вопросы