如果数据库数据过大,用java读取数据库,分页存入集合,每分页一次集合就被调用一次,这个java实现的方式是怎么样的?直接直接在sql语句上面加个for循环吗?for(){String sql = "SELECT ID,name, url From websites limit " + (i * 2) + ",2;";......}
2 回答
UYOU
TA贡献1878条经验 获得超4个赞
import java.sql.Connection; import java.sql.DriverManager; public class DBHelper { private static final String driver = "com.mysql.jdbc.Driver";//数据库驱动 private static final String url = "jdbc:mysql://localhost:3306/gumysql?useUnicon=true&characterEncoding=UTF-8"; private static final String username = "root"; private static final String password = "root"; static { try { Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } } private static Connection conn = null; //单例模式返回数据库连接 public static Connection getConnection() throws Exception { if(conn == null) { conn = DriverManager.getConnection(url, username, password); return conn; } else { return conn; } } }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class ReadDBPage { /** * @param pageNo 表示第几页 * @param pageSize 表示每页的数量 * @return */ public List<String> query(int pageNo, int pageSize) { //计算起始值,比如假如每页条数为5,第一页是0 - 4,第二页是5 - 9;。。。。 int pageStart = (pageNo - 1) * pageSize; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; String sql = " select * from compare limit ?,?; "; List<String> mapList = new ArrayList<String>(); try { conn = DBHelper.getConnection(); stmt = conn.prepareStatement(sql); //把参数设置到 ?号里面 stmt.setInt(1, pageStart); stmt.setInt(2, pageSize); rs = stmt.executeQuery(); while (rs.next()) { mapList.add(rs.getString("id")); } return mapList; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (rs != null) { try { rs.close(); rs = null; } catch (Exception e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); stmt = null; } catch (Exception e) { e.printStackTrace(); } } } } }
import java.util.List; public class Bootstrap { public static void main(String args[]){ ReadDBPage read = new ReadDBPage(); //查询第1页的数据,每页数据为5条 List<String> strList = read.query(1,5); //查询第2页的数据,每页数据为5条 List<String> strList2 = read.query(2,5); //查询第2页的数据,每页数据为4条 List<String> strList3 = read.query(2,4); System.out.println(strList); System.out.println(strList2); System.out.println(strList3); } }
添加回答
举报
0/150
提交
取消