JAVA技巧辅导(JNDI对数据库操作代码)
来源:优易学  2011-10-24 11:04:54   【优易学:中国教育考试门户网】   资料下载   IT书店
  代码如下:
  <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  <jsp:directive.page import="javax.sql.DataSource"/>
  <jsp:directive.page import="java.sql.Connection"/>
  <jsp:directive.page import="java.sql.ResultSet"/>
  <jsp:directive.page import="javax.naming.InitialContext"/>
  <jsp:directive.page import="java.sql.SQLException"/>
  <%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  %>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
  <head>
  <base href="<%=basePath%>">
  <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
  </head>
  <%
  DataSource ds = null;
  Connection conn = null;
  ResultSet rs = null;
  try{
  InitialContext ctx=new InitialContext();
  ds=(DataSource)ctx.lookup("java:comp/env/jdbc/e3java");
  conn= ds.getConnection();
  java.sql.Statement stmt = conn.createStatement();
  //青年人网站提示users必须是数据库已有的表,
  //这里的数据库前文提及的Data Source URL配置里包含的数据库。
  String strSql = "select * from product";
  rs= stmt.executeQuery(strSql);
  while(rs.next()){
  System.out.println(rs.getString(1));
  }
  }catch(Exception ex){
  ex.printStackTrace();
  }finally{
  try {
  rs.close();
  conn.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }
  %>
  <body>
  This is my JSP page. <br>
  </body>
  </html>

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训