静态全局对象
我有一个带有一个静态方法的类
建立连接
方法返回 Connection 对象以进行进一步的 JDBC 操作。是否有可能创建一个全局连接字段,并使用此方法的“返回”结果?我想在任何需要的地方使用这个字段。
public class Connection
{
public static Connection makeConnection() throws IOException, SQLException
{
try
{
Class.forName("org.postgresql.Driver");
Properties props = new Properties();
FileInputStream in = new FileInputStream("dataBase.properties");
props.load(in);
in.close();
String drivers = props.getProperty("jdbc.drivers");
if(drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username,password);
}
catch (ClassNotFoundException e)
{
return null;
}
catch(IOException e)
{
return null;
}
catch(SQLException e)
{
return null;
}
}
}
I've got class with one static method
makeConnection
The method returns Connection object for further JDBC operations. Is there a possibility, to create a global Connection field, with result of this method "return" ? I would like to use this field wherever I need.
public class Connection
{
public static Connection makeConnection() throws IOException, SQLException
{
try
{
Class.forName("org.postgresql.Driver");
Properties props = new Properties();
FileInputStream in = new FileInputStream("dataBase.properties");
props.load(in);
in.close();
String drivers = props.getProperty("jdbc.drivers");
if(drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username,password);
}
catch (ClassNotFoundException e)
{
return null;
}
catch(IOException e)
{
return null;
}
catch(SQLException e)
{
return null;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是可能的,但连接工厂比连接更好。
然而,静态变量对于连接的生命周期控制来说并不是一个好主意。
一个好的连接池会为你解决很多问题,比如并发访问、超时检测、回收活连接、自动清除死连接等。
It is possible, but the connection factory is better than a connection.
However, static variable is not a good idea for the lifecycle control of connections.
A good connection pool will take care many problem for you, such as the concurrent accessing, timed out detecting, recycle the alive connections, purging dead connections automatically.
你可以这样做:
这是你想要的吗?
You can do this:
Is that what you want?
这不是处理连接的方式...但它可能会让您了解如何解决类似的问题:
This is not the way to handle connections ... but it might give you an idea how to resolve similar kinds of problems:
您可以在静态初始化块中初始化静态变量:
You can initialize a static variable in a static initializer block: