我需要在作为会话bean实现的Java Web服务中建立数据库连接,我不确定我是否做得对.
我创建了一个类
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();
}
}
每当我需要连接时,我都会这样做
Connection cn = null;
try
{
cn = SQLUtils.getSQLConnection();
// use connection
}
finally
{
if (null != cn)
{
try
{
cn.close();
}
catch (SQLException e)
{
}
}
}
以这种方式使用它是否可以,或者我DataSource必须是bean的成员?
@Stateless
@WebService
public class TestBean {
private @Resource(name=dbName) DataSource m_ds;
}
如果这是一个nube问题,我很抱歉,但我对Java很新.提前致谢.
解决方法:
除了C风格的格式化,一些不必要的行和一些不良的异常处理,你可以这样做.
这是我如何做到的:
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.