У меня возникла проблема с возвратом строки из соединения с базой данных. В нем говорится, что 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;
}
}
Попробуйте эту строку return_statement = ""; – Abdelhak
'Statement stmt' не инициализирован' stmt = conn .createStatement(); 'missing –
Возможный дубликат http://stackoverflow.com/questions/14484550/java-variables-not-initialized-error – Rehman