JDBC连接池(Glassfish)的正确使用 [英] Proper usage of JDBC Connection Pool (Glassfish)
问题描述
我需要一个作为会话 bean 实现的 Java Web 服务中的数据库连接,但我不确定我是否做得对.
I need a database connection in Java Web service implemented as a session bean, and I'm not sure if I do it right.
我创建了一个类
public final class SQLUtils {
//.....
private static DataSource m_ds=null;
static
{
try
{
InitialContext ic = new InitialContext();
m_ds = (DataSource) ic.lookup(dbName); //Connection pool and jdbc resource previously created in Glassfish , dbName contains the proper JNDI resource name
}
catch (Exception e)
{
e.printStackTrace();
m_ds = null;
}
}
public static Connection getSQLConnection() throws SQLException
{
return m_ds.getConnection();
}
}
每当我需要连接时我都会
Whenever I need a connection I do
Connection cn = null;
try
{
cn = SQLUtils.getSQLConnection();
// use connection
}
finally
{
if (null != cn)
{
try
{
cn.close();
}
catch (SQLException e)
{
}
}
}
这样使用可以吗,还是我DataSource必须是bean的成员?
Is it ok to use it this way, or I DataSource must be a member of the bean ?
@Stateless
@WebService
public class TestBean {
private @Resource(name=dbName) DataSource m_ds;
}
很抱歉,如果这是一个麻烦的问题,但我对 Java 还很陌生.提前致谢.
I'm sorry if it is a nube question, but I'm pretty new to Java. Thanks in advance.
推荐答案
除了 C 风格的格式、一些不必要的行和有点糟糕的异常处理之外,你可以这样做.
Apart from the C-style formatting, a few unnecessary lines and a bit poor exception handling, you can just do so.
这是我的做法:
public final class SQLUtil {
private static DataSource dataSource;
// ..
static {
try {
dataSource = (DataSource) new InitialContext().lookup(name);
} catch (NamingException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
我在这里抛出 ExceptionInInitializerError
这样应用程序就会立即停止,这样您在尝试获取连接时就不需要面对无法解释的"NullPointerException
.
这篇关于JDBC连接池(Glassfish)的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!