当前位置: 代码迷 >> JavaScript >> JNDI获取数据源范例(jsp)
  详细解决方案

JNDI获取数据源范例(jsp)

热度:107   发布时间:2013-01-23 10:44:49.0
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();
?}
%>

?

?

?

?

  相关解决方案