色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

mysql jsp 分頁查詢

阮建安2年前23瀏覽0評論

在Web開發(fā)之中,經(jīng)常需要使用MySQL數(shù)據(jù)庫進行數(shù)據(jù)的存儲和查詢,而JSP作為一種Java語言的服務(wù)器端網(wǎng)頁技術(shù),也是經(jīng)常被用作Web開發(fā)之中。在JSP網(wǎng)頁之中,經(jīng)常會出現(xiàn)需要進行分頁顯示數(shù)據(jù)的需求,而這時就需要通過MySQL數(shù)據(jù)庫進行分頁查詢。以下是一個MySQL JSP 分頁查詢的實例。

<%
int currentPage = request.getParameter("currentPage") == null ? 1 : Integer.parseInt(request.getParameter("currentPage")); //獲取當(dāng)前頁碼,默認為1
int pageSize = 10; //每頁顯示10條數(shù)據(jù)
//連接MySQL數(shù)據(jù)庫
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, username, password);
//執(zhí)行SQL語句,獲取總記錄數(shù)
String sql1 = "SELECT COUNT(*) as total FROM mytable";
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery(sql1);
rs1.next();
int total = rs1.getInt("total");
//計算總頁數(shù)
int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
//執(zhí)行SQL語句,獲取當(dāng)前頁數(shù)據(jù)
String sql2 = "SELECT * FROM mytable LIMIT " + (currentPage - 1) * pageSize + "," + pageSize;
Statement stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(sql2);
%><% while (rs2.next()) { %><% } %>
IDNameAge
<%= rs2.getInt("id") %><%= rs2.getString("name") %><%= rs2.getInt("age") %>
<% //輸出分頁導(dǎo)航條 out.print("

"); if (currentPage == 1) { out.print("首頁 上一頁 "); } else { out.print("首頁"); out.print("上一頁"); } if (currentPage == totalPages) { out.print("下一頁 尾頁"); } else { out.print("下一頁"); out.print("尾頁"); } out.print("當(dāng)前第" + currentPage + "頁,共" + totalPages + "頁"); out.print("

"); %><% //關(guān)閉數(shù)據(jù)庫連接 rs1.close(); rs2.close(); stmt1.close(); stmt2.close(); conn.close(); %>

上面的代碼首先通過request.getParameter()方法獲取當(dāng)前頁碼,如果沒有指定則默認為1。然后通過JDBC API連接MySQL數(shù)據(jù)庫,并執(zhí)行兩條SQL語句獲取總記錄數(shù)和當(dāng)前頁數(shù)據(jù)。接著計算總頁數(shù),并使用while循環(huán)遍歷當(dāng)前頁數(shù)據(jù),使用HTML代碼將數(shù)據(jù)顯示在網(wǎng)頁之中。最后輸出分頁導(dǎo)航條,包括首頁、上一頁、下一頁和尾頁等鏈接,同時也顯示當(dāng)前頁碼和總頁數(shù)。最后關(guān)閉數(shù)據(jù)庫連接。