I am new to java and i have written the following:
package mypackage;
public class DBconnection {
Connection con = null;
public Connection getConnection() throws Exception, SQLException
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@zzz:1521:zzz","zzz", "zzz");
}
catch(Exception e)
{
}
return con;
}
public void removeConnection() throws SQLException
{
con.close();
}
}
When I am accesing the above code in a jsp page i have written following:
DBconnection dbconnect = new DBconnection();
dbconnect.getConnection();
I want to erite dbconnect.con.prepareStatement……(“sql query here”);// but error is coming as con is not public in mypackage.DBconnection ; cannot be accessed outside package
dbconnect.con is not accessible why????? I have declared variable con in public in the above code. Error is coming as con is not public in mypackage.DBconnection ; cannot be accessed outside package, how to resolve this??? please help me
In the code posted above,
conis package visible and not public. That is why you get the messagecannot be accessed outside package. To make it public you have to writeNote that if you are just going to call
you might end up with a
NullPointerException, sinceconis only initialized in thegetConnection()method. So I would advise to use the getter you createdOf course, the getter would need to be adjusted to only create a new connection when
conis stillnull. Otherwise it can just returncondirectly. TheremoveConnectionshould then after closing the connection setcontonull, otherwise calling thegetConnectionafter callingremoveConnectionwould return a closed connection, which is pretty useless