四个基本步骤
1.配置TomCat下的Context.xml文件
文件位置:TomCat>conf>Context.xml
<Resource name="jdbc/news" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/newsmanagersystem? useUnicode=true&characterEncoding=utf-8" />
2.配置web项目下的web.xml文件
文件位置:MyEclipse>webRoot>WEB-INF>web.xml
注意:web.xml下配置的 <res-ref-name> 节点的属性值一定要和TomCat下的Context.xml文件中的一致
<resource-ref>
<res-ref-name>jdbc/news</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
3.在TomCat下的Lib目录下导入连接数据库所需要的连接驱动
注意:连接不同的数据库所需的连接驱动不一样
4.使用lookup()方法获得数据库连接
public Connection getConnection() {
// 获取连接并捕获异常
try {
Context context=new InitialContext();
DataSource data=(DataSource)context.lookup("java:comp/env/jdbc/news");
if (conn == null || conn.isClosed())
conn =data.getConnection();
// conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;// 返回连接对象
}