打印本文 打印本文  关闭窗口 关闭窗口  
JAVA技巧(JNDI对数据库操作代码)
作者:佚名  文章来源:不详  点击数  更新时间:2008/11/1 20:42:04  文章录入:杜斌  责任编辑:杜斌

  代码如下:
  <%@ 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> 来源:考试大网
打印本文 打印本文  关闭窗口 关闭窗口