Java在數(shù)據(jù)庫操作中,查詢數(shù)據(jù)是很常見的操作。在查詢數(shù)據(jù)時,我們常常需要知道數(shù)據(jù)總條數(shù),以便在分頁時進行計算。下面,我們就來介紹一下如何使用Java查詢數(shù)據(jù)和獲取總條數(shù)。
//1.導入相關(guān)包 import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; //2.獲取數(shù)據(jù)庫連接 Connection conn = null; String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; try { // 加載MySql驅(qū)動 Class.forName("com.mysql.jdbc.Driver"); // 獲取數(shù)據(jù)庫連接 conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } //3.查詢數(shù)據(jù) PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select * from user limit ?,?"; try { pstmt = conn.prepareStatement(sql); //設置分頁參數(shù) pstmt.setInt(1, (page-1)*pageSize); pstmt.setInt(2, pageSize); //執(zhí)行查詢操作 rs = pstmt.executeQuery(); while(rs.next()){ //處理查詢結(jié)果 } } catch (SQLException e) { e.printStackTrace(); } finally{ try{ if(rs != null){ rs.close(); } if(pstmt != null){ pstmt.close(); } if(conn != null){ conn.close(); } }catch(SQLException e){ e.printStackTrace(); } } //4.獲取總條數(shù) int total = 0; String countSql = "select count(*) from user"; try { pstmt = conn.prepareStatement(countSql); rs = pstmt.executeQuery(); if(rs.next()){ total = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally{ try{ if(rs != null){ rs.close(); } if(pstmt != null){ pstmt.close(); } if(conn != null){ conn.close(); } }catch(SQLException e){ e.printStackTrace(); } }
以上就是Java查詢數(shù)據(jù)和獲取總條數(shù)的代碼示例。其中,對于查詢數(shù)據(jù),我們需要使用PreparedStatement來設置分頁參數(shù),并使用ResultSet遍歷查詢結(jié)果。對于獲取總條數(shù),我們需要執(zhí)行一個select count(*)的操作,并從ResultSet中獲取結(jié)果。
下一篇php ksc歌詞