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, con
is package visible and not public. That is why you get the message cannot be accessed outside package
. To make it public you have to write
public Connection con = null;
Note that if you are just going to call
dbconnect.con.prepareStatement
you might end up with a NullPointerException
, since con
is only initialized in the getConnection()
method. So I would advise to use the getter you created
dbconnect.getConnection().prepareStatement
Of course, the getter would need to be adjusted to only create a new connection when con
is still null
. Otherwise it can just return con
directly. The removeConnection
should then after closing the connection set con
to null
, otherwise calling the getConnection
after calling removeConnection
would return a closed connection, which is pretty useless
move this code to the constructor
public DBconnection(){
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@zzz:1521:zzz","zzz", "zzz");
}
catch(Exception e)
{
}
}
then make one object of it and share it to all your application classes and when you want to use connection
just call getConnecion()
from his object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.