1

这是我第一次使用 SQL Server,之前我在使用 MySQL,并且我在 tomcat 中成功创建了 db 连接池。我正在尝试使用相同的代码为 sql server 创建连接池。请指导我哪里出错了。

我正在尝试以 Windows 身份验证身份登录,我已将 sqljdbc_auth.dll 复制到 tomcat bin 目录中。

以下是我在 META-INF 下的 context.xml 文件中编写的代码:

Context antiJARLocking="true" path="">
    <Resource 
    auth="Container" 
    driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" 
    logAbandoned="true"
    maxActive="100"
    maxIdle="30" 
    maxWait="1000" 
    name="jdbc/mydb" 
    removeAbandoned="true"
    removeAbandonedTimeout="60"
    type="javax.sql.DataSource" 
    url="jdbc:sqlserver://localhost;integratedSecurity=true;" />
</Context>

下面是提供连接的java类:

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

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

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


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

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

当我尝试打电话时getConnection(),我得到了以下异常: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial Exception in thread "main" java.lang.NullPointerException at ConnectionPool.getConnection(ConnectionPool.java:39)

4

0 回答 0