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

JNDI获取数据源实例(jsp)

<%@ page language = "java" pageEncoding="utf-8"%>
<%@ page import = "java.util.*" %>
<%@ page import = "java.sql.*" %>
<%@ page import = "javax.sql.*" %>
<%@ page import = "javax.naming.*" %>
<%
?String jndi_name = "java:comp/env/jdbc/sid";
?String strSql = "select * from T_USER where rownum<2";

?Context ctx = null;
?DataSource ds = null;
?Connection conn = null;
?Statement stmt = null;
?ResultSet rs = null;
?try
?{
??ctx = new InitialContext();
??if( ctx == null ) out.println("no context");

??ds = (DataSource) ctx.lookup(jndi_name);
??if( ds == null ) out.println("no datasource");

??conn = ds.getConnection();
??stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,? ResultSet.CONCUR_READ_ONLY);
??rs = stmt.executeQuery(strSql);
??while(rs.next())
??{
???out.println("ID:" + rs.getString(1) +"<br />");
???out.println("姓名:" +rs.getString(2) +"<br />");
???out.println("年龄:" +rs.getString(3) +"<br />");
??}
?}
?catch(Exception ex)
?{
??ex.printStackTrace();
??out.println(ex.toString());
?}
?finally
?{
??if( rs != null )? rs.close();
??if( stmt != null ) stmt.close();
??if( conn != null)? conn.close();
??if( ctx != null ) ctx.close();
?}
%>

?

?

?

?