1、把sqljdbc4.jar放进Tomcat相应目录 /apache-tomcat-6.0.24/lib和应用程序类库中(必须两个位置)。
2、
更改配置文件:/WEB-INF/web.xml
插入一下内容:
EmployeeDB为数据库名
<resource-ref>
<description>
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the <Context>
configurartion for the web application.
</description>
<res-ref-name>
jdbc/EmployeeDB
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
3、建立单独的connFaction文件使用,如下所示:
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class ConnFactory {
public static Connection getConnection() throws Exception {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/ EmployeeDB ");
Connection conn = ds.getConnection();
return conn;
}
}
4、修改Tomcat资源工厂 apache-tomcat-6.0.24/conf /Context 文件。
<Context ...>
...
<Resource name="jdbc/EmployeeDB"
auth="Container"
type="javax.sql.DataSource"
username="dbusername"
password="dbpassword"
driverClassName="org.hsql.jdbcDriver"
url="jdbc:HypersonicSQL:database"
maxActive="8"
maxIdle="4"/>
...
</Context>
5、使用,如下:
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();