一、前言
其實,改寫后的jdbc data-source是運行在servlet中的,通過jndi去查找數據源。我用orion試的,將本站《java/jsp學習系列之六(mysql翻頁例子) 》 簡單改寫了一下。
二、配置
(1)jdbc
需要將用到的jdbc驅動copy到[orion]/lib目錄下
(2)data-source
在[orion]/config/data-sources.xml文件中加入如下:
〈data-source
class="com.evermind.sql.drivermanagerdatasource"
name="mysqldbpage"
location="jdbc/hypersoniccoreds"
xa-location="jdbc/xa/hypersonicxads"
ejb-location="jdbc/mysqldbpage"
connection-driver="org.gjt.mm.mysql.driver"
username="root"
password=""
url="jdbc:mysql://localhost/test"
inactivity-timeout="30"
/〉
需要注意的是:
(1)ejb-location這個后面的“jdbc/mysqldbpage”是jndi要來查找的。
(2)connection-driver為jdbc數據庫驅動
(3)url是jdbc中的url
(4)username為數據庫用戶名
(5)password為用戶密碼
(6)inactivity-timeout為數據庫連接超時,默認為30秒
對于其他的地方不要改。
三、改寫后的代碼如下:
<%@ page contenttype="text/html;charset=gb2312" %>
<%@ page import="java.sql.*, javax.sql.datasource, javax.naming.initialcontext" %>
<%
//建立一個jndi查找對象
initialcontext jndi_context = new initialcontext();
//jndi查找數據源
datasource ds = (datasource) jndi_context.lookup("jdbc/mysqldbpage");
//得到一個數據源連接
connection conn = ds.getconnection();
int intpagesize; //一頁顯示的記錄數
int introwcount; //記錄總數
int intpagecount; //總頁數
int intpage; //待顯示頁碼
java.lang.string strpage;
int i;
//設置一頁顯示的記錄數
intpagesize = 2;
//取得待顯示頁碼
strpage = request.getparameter("page");
if(strpage==null){
//表明在querystring中沒有page這一個參數,此時顯示第一頁數據
intpage = 1;
} else{
//將字符串轉換成整型
intpage = java.lang.integer.parseint(strpage);
if(intpage<1) intpage = 1;
}
// 得到結果
stmt = conn.createstatement();
resultset sqlrst = stmt.executequery("select f1 from test");
//獲取記錄總數
sqlrst.last();
introwcount = sqlrst.getrow();
//記算總頁數
intpagecount = (introwcount+intpagesize-1) / intpagesize;
//調整待顯示的頁碼
if(intpage>intpagecount)
intpage = intpagecount;
%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title>jsp數據庫操作例程 - 數據分頁顯示 - jdbc 2.0 - mysql</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<th>姓名</th>
</tr>
<% if(intpagecount>0)
{
//將記錄指針定位到待顯示頁的第一條記錄上
sqlrst.absolute((intpage-1) * intpagesize + 1);
//顯示數據
i = 0;
while(i<intpagesize && !sqlrst.isafterlast()){ %>
<tr>
<td>
<%=sqlrst.getstring(1)%>
</td>
</tr>
<% sqlrst.next();
i++;
}
}
%>
</table>
第<%=intpage%>頁 共<%=intpagecount%>頁
<%if(intpage<intpagecount){%><a href="mysqlpage.jsp?page=<%=intpage+1%>">下一頁</a><%}%>
<%if(intpage>1){%><a href="mysqlpage.jsp?page=<%=intpage-1%>">上一頁</a><%}%>
</body>
</html>
<%
//關閉結果集
sqlrst.close();
%>
三、怎么去運行?
見前文《java/jsp學習系列之五(jdbc-odbc翻頁例子)》。
注意:mysql數據庫為test,中間有個表test,有個字段f1(varchar)
新聞熱點
疑難解答