Reputation: 97
Im trying to create a class that will allow me to connect to mySQL DB via JDBC but the object that Connection returns is null. I believe that the error is that I do not use error information messages inside the Exceptions but instead return null values.
Removing the return null;
statement caused an error: This method must return a result of type Connection
return conn;
} catch (Exception e) {
// return null;
e.printStackTrace();
}
}
Adding both return null;
and e.printStackTrace();
caused an Unreachable code error
return conn;
} catch (Exception e) {
return null;
e.printStackTrace();
}
My code :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ServerConn
{
public Connection OpenDatabase() {
try {
Class.forName( "com.mysql.jdbc.Driver" ) ;
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/promitheas?user=me&password=iwontsay") ;
return conn;
} catch (Exception e) {
return null;
}
}
public ResultSet dbQuery(String sql)
{
Connection cn = OpenDatabase();
if (!(cn == null)){
try {
Statement stmt = cn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs;
} catch (Exception e) {
return null;}
}
return null;
}
public ServerConn(){}
}
Upvotes: 1
Views: 3860
Reputation: 6802
its better (less confusing) to use a single return statement.
public Connection OpenDatabase() {
Connection conn =null;
try {
Class.forName( "com.mysql.jdbc.Driver" ) ;
conn = DriverManager.getConnection("jdbc:mysql://localhost/promitheas?user=me&password=iwontsay") ;
} catch (Exception e) {
e.printStackTrace();
}
return conn;//returns null in case of exception.
}
Upvotes: 1
Reputation: 121998
return conn;
} catch (Exception e) {
return null; //returning
e.printStackTrace(); // what should I do as you are already returning.
}
That is illeagal. And causes Unreachable code error
, Since you are writing code after return
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
Besides that returning from catch block is smelling like a design issue. Rethink of it once.
Upvotes: 1