JAVA技巧(JNDI对数据库操作代码) |
|
www.nanhushi.com 佚名 不详 |
代码如下: <%@ 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> 来源:考试大网
|
|
|
文章录入:杜斌 责任编辑:杜斌 |
|
上一篇文章: JAVA技巧(在jstl标签中forEach标签遍历Map) 下一篇文章: JAVA基础Comparable |
【字体:小 大】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 |
|
|