日期:2014-05-16  浏览次数:20377 次

JNDI连接数据库的配置步骤

步骤:
预备:把JDBC的数据库连接JAR包放在Tomcat的lib目录下
1.Tomcat->conf->context.xml
<Context>
?<Resource name="jdbc/(数据库名称)" auth="Container" type="javax.sql.DataSource"
?maxActive="100" maxIdle="10" maxWait="10000"
?driverClassName="数据库连接字符串"
?url="连接url"
?user="sa"
?password=""
?/>
</Context>
eg:
<Context>
?<Resource name="jdbc/accp" auth="Container"
?type="javax.sql.DataSource" maxActive="100" maxIdle="10"
?maxWait="10000" username="sa" password=""
?driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
?url="jdbc:sqlserver://localhost:1433;DatabaseName=accp" />
</Context>

2.Project->web.xml
<web-app>
?<resource-ref>
?<res-ref-name>jdbc/(数据库名称)</res-ref-name>
?<res-type>javax.sql.DataSource</res-type>
?<res-auth>Container</res-auth>
</web-app>
eg:
<web-app>
?<resource-ref>
? ?<res-ref-name>jdbc/accp</res-ref-name>
? ?<res-type>javax.sql.DataSource</res-type>
? ?<res-auth>Container</res-auth>
? ?</resource-ref>
</web-app>

3.Project->(RelationCode)关键代码
try{
Context ct=new InitialContext();
DataSource ds=(DataSource)ct.lookup("jdbc:comp/env/(ResourceName)");
Connection conn=ds.getConnection();
}catch(NamingException ne){
?ne.printStackTrace();
}catch(SQLException se){
?se.printStackTrace();
}