第一步:
//初始化文
Context ctx = new InITALContext ();
// l连接相关数据源对象
DataSource ds = (DataSource) ctx .lookup(java:comp/env/jdbc/new)
//数据连接
try {
Connection con = test.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select *from name");
while (rs.next()) {
out.print(rs.getInt(1));
out.print(rs.getString(2));
out.print(rs.getString(3));
}
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
out.print(e);
}
数据源的配置
配置Tomcat安装目录 、conf/context.xml文件
<Resource
name="jdbc/new" auth="Container"
type="javax.sql.DataSource" MaxActive="100"
maxIdle="30" maxWait="1000"
username= "root"
password ="123"
url ="jdbc:mysql://127.0.0.1/3306/dbn
/>
</context>
配置/webRoot/WRB-INF/WEB.xml
<web-app>
<resource-ref>
<description>new DataSource</description>
<res-ref-name>jdbc/new<ref-name>
<ref-type>javax.sql.DataSource</ref-type>
<ref-auth>Container</ref-auth>
</resource-ref>
</web-app>
编辑jsp代码, 实现查找数据源
Context ctx = new InialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp:env/jdbc/new")
Connection con = ds.getConnection();
常见错误
第一
错误提示
cannt create jdbc driver of class(不能创建驱动)
解决方案 :
检查context.xml文件的数据源配置的文件信息
错误提示
Name jdbc is not bound in this Context (未找到数据源)
解决方案
数据源名称与配置文件名称不一致 , 确保context.xml 文件的名成与数据源名称
程序调试lookup();一定要使用前缀(java:comp/env/)
c错误提示
Cannot load driver class (不能加载驱动)
解决方案
要把数据库连接包添加到tomcat 的lib目录下