初始化连接池时出现NullPointerException

问题描述 投票:0回答:1

我在context.xml中有包含数据库连接信息的设置

<Context>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

        <Resource 
        name="jdbc/*(my username)*" 
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
        auth="Container" 
        type="javax.sql.DataSource"
        removeAbandoned="true" 
        removeAbandonedTimeout="30" 
        maxACtive="100"
        maxIdle="30" 
        maxWait="10000" 
        username= *(my username)*
        password= *(my password)*
        driverClassName="com.ibm.db2.jcc.DB2Driver" 
        url="jdbc:db2://(my server host):50000/*(my username)*">
    </Resource>
</Context>

在连接池中,我创建了一个类来初始化并将其连接到数据库。错误开始于getConnection()的方法。 NullPointerException

返回中错误的方式为datasource.getConnection()
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class ConnectionPool {
    private static ConnectionPool pool = null;
    private static DataSource dataSource = null;

    private ConnectionPool() {
        try {
            InitialContext ic = new InitialContext();
            dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/COMPANY");
            System.out.print(dataSource);
        } catch (NamingException e) {
            System.out.println(e);
        }
    }

    public static synchronized ConnectionPool getInstance() {
        if (pool == null) {
            pool = new ConnectionPool();
        }
        return pool;
    }

    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            System.out.println(e);
            return null;
        }
    }

    public void freeConnection(Connection c) {
        try {
            c.close();
        } catch (SQLException e) {
            System.out.println(e);
        }
    }
}

我用Eclipse的Perspective Database Development测试了数据库连接,并且能够连接并完成所有查询。

此外,它在输出中给了我这个错误

SEVERE: Unable to create initial connections of pool.
java.sql.SQLException: No suitable driver found for jdbc:db2://db2.cecsresearch.org:50000/(my username)

尽管我在lib文件夹和类路径中有jar库文件。

java nullpointerexception database-connection connection-pooling connection-pool
1个回答
0
投票

nullpointer只是由以下问题引起的:

java.sql.SQLException: No suitable driver found for jdbc:db2://db2.cecsresearch.org:50000/(my username)
© www.soinside.com 2019 - 2024. All rights reserved.