微軟的.NET平臺(tái)上面的數(shù)據(jù)訪問有一個(gè)特點(diǎn),就是數(shù)據(jù)查詢的結(jié)果,可以放在內(nèi)存中,以XML格式進(jìn)行描述,不需要一直與數(shù)據(jù)庫保持在線連接,用DataSet + Data Adapter來實(shí)現(xiàn)!
而在JDBC中,我們通常使用javax.sql.ResultSet類來存放放回的數(shù)據(jù),它的流程和生命周期如下:
使用ResultSet來返回?cái)?shù)據(jù)庫查詢結(jié)果 |
Client |
--> |
Connection |
--> |
Statement |
--> |
JDBC Driver |
--+ |
|
Database |
Client |
<-- |
Parsing |
<-- |
ResultSet |
<-- |
JDBC Driver |
--+ |
|
|
|
|
|
|
|
|
|
Connection lifecycle |
|
|
|
|
|
|
ResultSet lifecycle |
|
|
我們可以看到,這樣會(huì)長(zhǎng)期占用數(shù)據(jù)庫連接的資源,是一個(gè)有點(diǎn)不爽的問題...
其實(shí),在JSTL中提供了另外一種機(jī)制,讓我們?cè)诜祷夭樵兘Y(jié)果到表示層的時(shí)候,可以做到離線使用!它就是javax.servlet.jsp.jstl.sql.Result類!
1 <%@taglib uri="http://java./jsp/jstl/core" prefix="c"%> 2 <%@page contentType="text/html; charset=UTF-8"%> 3 <%@page import="java.sql.Connection"%> 4 <%@page import="java.sql.DriverManager"%> 5 <%@page import="java.sql.ResultSet"%> 6 <%@page import="java.sql.SQLException"%> 7 <%@page import="java.sql.Statement"%> 8 <%@page import="javax.servlet.jsp.jstl.sql.Result"%> 9 <%@page import="javax.servlet.jsp.jstl.sql.ResultSupport"%> 10 <% 11 // 暫且把這個(gè)下面的內(nèi)容看作多層架構(gòu)中的DAO好了,我偷懶了! 12 Connection conn = null; 13 Statement stmt = null; 14 ResultSet rs = null; 15 String strDbUrl 16 = "jdbc:mysql://localhost/tutorial?user=tutorial&password=tutpwd"; 17 try { 18 //開始與數(shù)據(jù)庫作查詢 19 Class.forName("com.mysql.jdbc.Driver").newInstance(); 20 conn = DriverManager.getConnection(strDbUrl); 21 stmt = conn.createStatement(); 22 String strSql = "SELECT * FROM R_TUT_USERS"; 23 rs = stmt.executeQuery(strSql); 24 //把ResultSet轉(zhuǎn)化成Result 25 Result userData = ResultSupport.toResult(rs); 26 //當(dāng)我們把結(jié)果放到某個(gè)Model bean后,就可以關(guān)閉數(shù)據(jù)庫連接了. 27 //為了簡(jiǎn)化,我們暫且把pageContext看作Model Bean好了! 28 pageContext.setAttribute("userData", userData); 29 } 30 catch (Exception ex) { 31 // handle any errors 32 System.out.println("SQLException: " + ex.getMessage()); 33 } 34 finally { 35 try { 36 if (rs != null) { 37 rs.close(); 38 } 39 if (stmt != null) { 40 stmt.close(); 41 } 42 if (conn != null) { 43 conn.close(); 44 } 45 } 46 catch (SQLException ex) { 47 System.out.println("SQL Exception: " + ex.getMessage()); 48 } 49 } 50 //DAO的邏輯結(jié)束 51 %> 52 <html> 53 <head> 54 <title>test</title> 55 </head> 56 <body> 57 58 <c:forEach items="${userData.rows}" var="user"> 59 <c:out value=‘${user.name}‘/> 60 </c:forEach> 61 </body> 62 </html> |