在程序中访问(WebSphere6.1)Was中数据源

在程序中访问(WebSphere6.1)Was中数据源
2012年6月21日15:21:59

程序代码下载:
http://www.blogjava.net/Files/heyang/ViewDsSample.zip
注意这个程序是RSA中的Dynamic Web Project


如果需要建立数据源,请参考:
http://www.blogjava.net/heyang/archive/2012/06/21/381257.html

如果需要建立JDBC Provider,请参考:
http://www.blogjava.net/heyang/archive/2012/06/21/381254.html

由于是示例代码,所以比较简单,功能就是访问数据库中一张表,然后把数据在表格中显示出来。index.jsp中的代码如下:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<% @ page language = " java "  autoFlush = " true "  isThreadSafe = " true "  buffer = " 10kb "   %>
<% @ page import = " javax.servlet.http.* " %>
<% @ page import = " java.util.*,java.lang.*,java.math.* " %>


<% @ page import = " java.sql.Connection " %>
<% @ page import = " java.sql.DriverManager " %>
<% @ page import = " java.sql.Statement " %>
<% @ page import = " javax.naming.Context " %>
<% @ page import = " javax.naming.InitialContext " %>
<% @ page import = " javax.sql.DataSource " %>
<% @ page import = " java.sql.ResultSet " %>


< html >
    
< head >
        
< title > View DataSource In Was </ title >
    
</ head >
    
    
< body >
        
< table  width ="100px"  border ="1" >
        
< caption > Visit the data in DataSource </ caption >     
        
< thead >
        
< tr >
            
< td  width ="50px" > Id </ td >
            
< td  width ="50px" > Name </ td >
        
</ tr >     
        
</ thead >
        
< tbody >
        
<%
            Context ctx
=   new  InitialContext();
            DataSource ds 
=  (DataSource) ctx.lookup( " jdbc/localdb2 " ); // 注意这里需要和数据源配置中的jndi名对应上。
            
            Connection con 
=  ds.getConnection();
            
String  sql  =   " select * from SYSTEM.TESTTB0619 " ;
            
            Statement stmt 
=  con.createStatement();
            ResultSet rs
= stmt.executeQuery(sql);
            
            
while  (rs.next()) {
                
String  id  =  rs.getString( " id " );
                
String  name  =  rs.getString( " name " );
                
                out.println(
" <tr> " );
                out.println(
" <td> " + id + " </td> " );
                out.println(
" <td> " + name + " </td> " );
                out.println(
" </tr> " );
            }
            
            
            rs.close();
            stmt.close();
            con.close();
        
%>
        
</ tbody >
        
</ table >
    
</ body >
</ html >

首页显示效果如下:

你可能感兴趣的:(在程序中访问(WebSphere6.1)Was中数据源)