[英]oracle database connection in java
I am new to java and i have written the following: 我是java的新手,并且编写了以下内容:
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: 当我在jsp页面中访问以上代码时,我写了以下内容:
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 ; 我想设置dbconnect.con.prepareStatement ......(“ sql query here”); //但由于con在mypackage.DBconnection中不是公共的,因此出现错误。 cannot be accessed outside package
不能在包外访问
dbconnect.con is not accessible why????? dbconnect.con无法访问,为什么???? I have declared variable con in public in the above code.
我在上面的代码中公开声明了变量con。 Error is coming as con is not public in mypackage.DBconnection ;
由于con在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. 在上面发布的代码中,
con
是程序包可见的而不是公共的。 That is why you get the message cannot be accessed outside package
. 这就是为什么您
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. 您可能最终会遇到
NullPointerException
,因为con
仅在getConnection()
方法中初始化。 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
. 当然,将需要调整getter以仅在
con
仍然为null
时创建新连接。 Otherwise it can just return con
directly. 否则,它可以直接返回
con
。 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 然后,在关闭连接集
con
后将removeConnection
设置为null
,否则在调用removeConnection
之后调用getConnection
将返回一个关闭的连接,这是毫无用处的
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 然后创建一个对象并将其共享给所有应用程序类,当您要使用
connection
只需从其对象调用getConnecion()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.