资源描述
JNDI方法连接数据库
用了JNDI之后的做法:首先,在在J2EE容器中配置JNDI参数,定义一个数据源,也就是JDBC引用参数,给这个数据源设置一个名称;然后,在程序中,通过数据源名称引用数据源从而访问后台数据库
1.创建一个web工程,把mysql的驱动包放到lib中,或者在Tomcat6.0的安装目录下的lib文件夹放入mysql的驱动包。
2. 在Tomcat6.0的安装目录下,找到conf/ context.xml,打开context.xml进行修改:
在<context> </context>中加入如下内容:
<Context>
<Resource name=" test"//JNDI的名字 随便写
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/info "
username="root" //访问数据库的用户名
password="dp" //数据库密码
maxActive="10" //连接池的最大数据库连接数。设为0表示无限制。
maxIdle="30" //maxIdle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
maxWait="10000" /> //maxWait最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。</Context>
2 在项目的WEB-INF/web.xml,中修改web.xml:
在<web-app></wep-app>中加入
<resource-ref>
<description>DB Connection </description>//描述(可不要)
<res-ref-name>test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4.JSP测试代码 index.jsp
<%@page import="java.sql.*" %>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>
<%try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/message");//获得数据源
Connection conn = ds.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from tb_message");
while(rs.next()){
out.println(rs.getString(3) + "<br/>");
}
out.println("测试成功");
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
%>
展开阅读全文