一、通用分页后台查询方法代码实现
首先导入jar包连接数据库:
package com.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 提供了一组获得或关闭数据库对象的方法 * */ public class DBAccess { private static String driver; private static String url; private static String user; private static String password; static {// 静态块执行一次,加载 驱动一次 try { InputStream is = DBAccess.class .getResourceAsStream("config.properties"); Properties properties = new Properties(); properties.load(is); driver = properties.getProperty("driver"); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("pwd"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 获得数据连接对象 * * @return */ public static Connection getConnection() { try { Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } public static void close(ResultSet rs) { if (null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Statement stmt) { if (null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn) { if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } public static void close(Connection conn, Statement stmt, ResultSet rs) { close(rs); close(stmt); close(conn); } public static boolean isOracle() { return "oracle.jdbc.driver.OracleDriver".equals(driver); } public static boolean isSQLServer() { return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver); } public static boolean isMysql() { return "com.mysql.jdbc.Driver".equals(driver); } public static void main(String[] args) { Connection conn = DBAccess.getConnection(); DBAccess.close(conn); System.out.println("isOracle:" + isOracle()); System.out.println("isSQLServer:" + isSQLServer()); System.out.println("isMysql:" + isMysql()); System.out.println("数据库连接(关闭)成功"); } }
config.properties解析文件
(我用的是#mysql5 sys是我的数据库名称 pwd是数据库密码 root是数据库登录名)
#oracle9i #driver=oracle.jdbc.driver.OracleDriver #url=jdbc:oracle:thin:@localhost:1521:ora9 #user=test #pwd=test #sql2005 #driver=com.microsoft.sqlserver.jdbc.SQLServerDriver #url=jdbc:sqlserver://localhost:1423;DatabaseName=test #user=sa #pwd=sa #sql2000 #driver=com.microsoft.jdbc.sqlserver.SQLServerDriver #url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB #user=sa #pwd=888888 #mysql5 driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/sys?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123
接下来就是实体类:Book.java
package com.entity; public class Book { private int bid; private String bname; private float price; @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; } public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Book(int bid, String bname, float price) { super(); this.bid = bid; this.bname = bname; this.price = price; } public Book() { super(); } }
分页的工具类:PageBean .java
package com.util; /** * 分页工具类 * */ public class PageBean { private int page = 1;// 页码 private int rows = 10;// 页大小 private int total = 0;// 总记录数 private boolean pagination = true;// 是否分页 public PageBean() { super(); } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public void setTotal(String total) { this.total = Integer.parseInt(total); } public boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } /** * 获得起始记录的下标 * * @return */ public int getStartIndex() { return (this.page - 1) * this.rows; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; } }
判断字符串的工具类:StringUtils.java
package com.util; public class StringUtils { // 私有的构造方法,保护此类不能在外部实例化 private StringUtils() { } /** * 如果字符串等于null或去空格后等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isBlank(String s) { boolean b = false; if (null == s || s.trim().equals("")) { b = true; } return b; } /** * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isNotBlank(String s) { return !isBlank(s); } }
接下来就是使用泛型:basedao.java
package com.dengrenli.dao; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.util.DBAccess; import com.util.PageBean; /** * T代表你要对哪个实体类对应表进行分页查询 * @author 2018111801 * * @param <T> */ public class BaseDao<T> { /** * * @param sql 查询不同的实体类那么对应的sql语句不同,所以需要传递 * @param clz 生产出不同的实体类对应的实例,然后装进list容器中返回 * @param pageBean 决定是否分页 * @return * @throws SQLException * @throws IllegalAccessException * @throws InstantiationException */ public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{ Connection con= DBAccess.getConnection(); PreparedStatement ps = null; ResultSet rs=null; if(pageBean!=null && pageBean.isPagination()) { // 3、考虑该方法可以进行分页 //需要分页 // 3.1算符合总记录数 String consql=getconsql(sql); ps = con.prepareStatement(consql); rs=ps.executeQuery(); if(rs.next()) { // 算总记录数 pageBean.setTotal(rs.getLong(1)+""); } String setsql=getsetsql(sql,pageBean); ps = con.prepareStatement(setsql); rs=ps.executeQuery(); }else { ps = con.prepareStatement(sql); rs=ps.executeQuery(); } List<T> list=new ArrayList<>(); T t; while(rs.next()) { //list.add(new Book(rs.getInt("bid"),rs.getString("bname") , rs.getFloat("price"))); //1:实列化一个对象(该对象是空的,里面的属性没有值) //2:去book的所有属性,然后给其赋值 //2.1 获取所有属性对象 //2.2 给属性对象赋值 //3:然后装进list //给属性赋值 t= (T)clz.newInstance(); Field[] fileds = clz.getDeclaredFields(); for (Field field : fileds) { field.setAccessible(true); field.set(t, rs.getObject(field.getName())); } list.add(t); } DBAccess.close(con, ps, rs); return list; } private String getsetsql(String sql, PageBean pageBean) { //利用原生sql拼接出符合条件的结果集的查询sql return sql+" limit "+ pageBean.getStartIndex()+","+pageBean.getRows(); } private String getconsql(String sql) { //获取符合条件的总记录数的sql语句 return "select count(*) from ("+sql+")t"; } }
接下来这个类继承BaseDao:BookDao.java
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.entity.Book; import com.util.BaseDao; import com.util.PageBean; import com.util.StringUtils; public class BookDao extends BaseDao<Book> { public List<Book> list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{ String sql="select * from t_mvc_book where true "; String bname=book.getBname(); if(StringUtils.isNotBlank(bname)) { sql+=" and bname like '%"+bname+"%' "; } return super.executeQuery(sql, Book.class, pageBean); } // 测试方法 public static void main(String[] args) { BookDao dao=new BookDao(); Book book=new Book(); // book.setBname("斗破"); PageBean pageBean=new PageBean(); //默认为true的 如果给它赋值为false的就不会进行分页查询 //pageBean.setPagination(false); pageBean.setPage(3); pageBean.setRows(5); try { List<Book> list=dao.list(book,pageBean); //获取总条数 System.out.println(pageBean.getTotal()); for (Book book2 : list) { System.out.println(book2); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }