当前位置:   article > 正文

使用JDBC连接并操作MySQL,SQL server,oracle三大数据库。以及分页查询展示_jdbc连接sql server数据库

jdbc连接sql server数据库

jdbc相关:

jdbc连接SQL server数据库:

首先要对SQL server的一些配置进行更改:

找到SQL server的配置管理器:然后点击进去。

找到SQL server网络配置下一级的mssqlserver的协议。把右边的,TCP/Ip的状态右击改为启动。
也可以点击属性设置,找到ip地址

把常用的ip10/ip6/ip4的地址改为本机。127.0.0.1
不能改成localhost

改完这些之后,重启SQL server服务
sqlserver(mssqlserver)

在java程序中连接SQL server:

新建一个类:

  1. public class SqlServerUtils {
  2.    public static Connection  con = null;
  3.    public static  Statement state = null;
  4.    public static  ResultSet rs = null;
  5.    static {
  6.        try {
  7.            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  8.       } catch (ClassNotFoundException e) {
  9.            e.printStackTrace();
  10.       }
  11.   }
  12.    //连接数据库
  13.    public static Connection getCon(){
  14.        String url = "jdbc:sqlserver://localhost:1433;databaseName=meitao";
  15.        //databaseName = 你要连接的数据库名字
  16.        String username = "sa"; //要连接的用户名
  17.        String password = "123"; //密码
  18.        try {
  19.            con = DriverManager.getConnection(url,username,password);
  20.       } catch (SQLException throwables) {
  21.            throwables.printStackTrace();
  22.       }
  23.        return con;
  24.   }
  25.    //关闭连接
  26.    public static void close(Connection con,Statement state,ResultSet rs){
  27.        try {
  28.            if (rs != null){
  29.                rs.close();
  30.           }
  31.            if (state != null){
  32.                state.close();
  33.           }
  34.            if (con != null){
  35.                con.close();;
  36.           }
  37.       }catch (Exception e){
  38.            e.printStackTrace();
  39.       }
  40.   }
  41. }

新建dao层完成增删改查以adminDao为例:

  1. public class AdminDao {
  2.    //添加admin
  3.  public Integer addAdmin(Admin admin){
  4.      Connection con = SqlServerUtils.getCon();
  5.      PreparedStatement ps = null;
  6.      Integer result = null;
  7.      String sql = "insert into admin values(?,?,?)";
  8.      try {
  9.          ps = con.prepareStatement(sql);
  10.          //设置问号的值
  11.          ps.setInt(1,admin.getAdminId());
  12.          ps.setString(2,admin.getAdminName());
  13.          ps.setString(3,admin.getPwd());
  14.          //执行sql语句
  15.          int rows = ps.executeUpdate();
  16.          if (rows > 0){
  17.              return rows;
  18.         }else {
  19.              return 0;
  20.         }
  21.     } catch (SQLException throwables) {
  22.          throwables.printStackTrace();
  23.     }finally {
  24.         SqlServerUtils.close(con,ps,null);
  25.     }
  26.      return 0;
  27. }
  28.    
  29.    //删除
  30.    public Integer delAdminById(Integer id){
  31.      Connection con = SqlServerUtils.getCon();
  32.      PreparedStatement ps = null;
  33.      ResultSet rs = null;
  34.      String sql = "delete from admin where adminid = ? ";
  35.        try {
  36.            ps = con.prepareStatement(sql);
  37.            ps.setInt(1,id);
  38.            int rows = ps.executeUpdate();
  39.            if (rows > 0){
  40.                System.out.println("删除成功");
  41.           }else {
  42.                System.out.println("删除失败");
  43.           }
  44.       } catch (SQLException throwables) {
  45.            throwables.printStackTrace();
  46.       }finally {
  47.            SqlServerUtils.close(con,ps,null);
  48.       }
  49.    
  50.    
  51.  //查找admin
  52.    public Admin getAdminByNameAndPwd(String name,String password){
  53.      Connection con = SqlServerUtils.getCon();
  54.      PreparedStatement ps = null;
  55.      ResultSet rs = null;
  56.      //String sql = "select * from admin where adminid = '"+id+"'";
  57.        String sql = "select * from admin where adminname = ? and password = ?";
  58.        try {
  59.            ps = con.prepareStatement(sql);
  60.            ps.setString(1,name);
  61.            ps.setString(2,password);
  62.            rs = ps.executeQuery();
  63.            if (rs.next()){
  64.                int adminId = rs.getInt(1);
  65.                String adminName = rs.getString(2);
  66.                String pwd = rs.getString(3);
  67.                return new Admin(adminId,adminName,pwd);
  68.           }
  69.       } catch (SQLException throwables) {
  70.            throwables.printStackTrace();
  71.       }finally {
  72.            SqlServerUtils.close(con,ps,rs);
  73.       }
  74.        return null;
  75.   }
  76.    //查询全部
  77.    public List<Admin> getAdminList(){
  78.        Connection con = SqlServerUtils.getCon();
  79.        PreparedStatement ps = null;
  80.        ResultSet rs = null;
  81.      String sql = "select * from admin";
  82.        try {
  83.            ps = con.prepareStatement(sql);
  84.             rs = ps.executeQuery();
  85.            while (rs.next()){
  86.                int adminId = rs.getInt("adminid");
  87.                String adminName = rs.getString("adminName");
  88.                String pwd = rs.getString("password");
  89.                System.out.println("编号:"+adminId+" 姓名:"+adminName+" 密码:"+pwd);
  90.           }
  91.       } catch (SQLException throwables) {
  92.            throwables.printStackTrace();
  93.       }finally {
  94.            SqlServerUtils.close(con,ps,rs);
  95.       }
  96.        return  null;
  97.   }
  98.    //修改admin
  99.    public Integer updateAdmin(Admin admin){
  100.      Connection con = SqlServerUtils.getCon();
  101.      PreparedStatement ps = null;
  102.      Integer result = null;
  103.      String sql = "update admin set adminname = ? , password = ? where adminid = ?";
  104.        try {
  105.            ps = con.prepareStatement(sql);
  106.            ps.setString(1,admin.getAdminName());
  107.            ps.setString(2,admin.getPwd());
  108.            ps.setInt(3,admin.getAdminId());
  109.            result = ps.executeUpdate();
  110.       } catch (SQLException throwables) {
  111.            throwables.printStackTrace();
  112.       }finally {
  113.            SqlServerUtils.close(con,ps,null);
  114.       }
  115.        return result;
  116.   }
  117. }

新建测试类进行测试:

  1. public class sqlServiceTest {
  2.    public static void main(String[] args) {
  3.       //getAll();
  4. //       Admin admin = new Admin(3,"里哈哈","133232");
  5. //       updateAdmin(admin);
  6.        //getAdminByNameAndPwd("孙道恩","111");
  7.        delById(3);
  8.   }
  9.    //添加数据
  10.    public static void addAdmin(){
  11.        Admin admin = new Admin(3,"浮动","8989");
  12.        AdminDao adminDao = new AdminDao();
  13.        Integer rows = adminDao.addAdmin(admin);
  14.        if (rows > 0){
  15.            System.out.println("添加成功");
  16.       }else {
  17.            System.out.println("添加失败");
  18.       }
  19.   }
  20.    //单个查询
  21.    public static void getAdminByNameAndPwd(String name,String pwd){
  22.        AdminDao adminDao = new AdminDao();
  23.        Admin adminByNameAndPwd = adminDao.getAdminByNameAndPwd(name, pwd);
  24.        System.out.println(adminByNameAndPwd);
  25.   }
  26.    //查询全部
  27.    public static void getAll(){
  28.        AdminDao adminDao = new AdminDao();
  29.        List<Admin> adminList = adminDao.getAdminList();
  30.   }
  31.    //修改信息
  32.    public static void updateAdmin(Admin admin){
  33.        Integer rows = new AdminDao().updateAdmin(admin);
  34.        if (rows > 0){
  35.            System.out.println("修改成功");
  36.       }else {
  37.            System.out.println("修改失败");
  38.       }
  39.   }
  40.    //根据id删除
  41.    public static void delById(Integer id){
  42.        AdminDao adminDao = new AdminDao();
  43.        adminDao.delAdminById(id);
  44.   }
  45. }

jdbc连接Oracle数据库:

在utils包中创建一个OracleUtils类:
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. public class OracleUtils{
  5.    public static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521/PDBORCL";
  6.    //后面的PDBORCl是要操作的pdb
  7.    //在navicate里面使用select name,open_mode from v$pdbs;查询全部找到这个pdb
  8.    //然后在执行下面的语句让此pdb打开alter pluggable database PDBORCL open;
  9.    public static final String USER = "c##sde2";
  10.    public static final String PASSWORD = "orcl";
  11.    
  12.    public static Connection getConnection(){
  13.        //加载驱动
  14.        try {
  15.            Class.forName("oracle.jdbc.OracleDriver");
  16.       }catch (ClassNotFoundException e){
  17.            e.printStackTrace();
  18.       }
  19.        //连接数据库
  20.        Connection con = null;
  21.        try {
  22.            con = DriverManager.getConnection(URL,USER,PASSWORD);
  23.       }catch (SQLException e){
  24.            e.printStackTrace();
  25.       }
  26.        System.out.println("连接成功");
  27.        return con;
  28.   }
  29. }
  30. //关闭连接
  31.    public static void close(Connection con, Statement state,ResultSet rs){
  32.        if (rs != null){
  33.            try {
  34.                rs.close();
  35.           } catch (SQLException throwables) {
  36.                throwables.printStackTrace();
  37.           }
  38.       }
  39.        if (state != null){
  40.            try {
  41.                state.close();
  42.           } catch (SQLException throwables) {
  43.                throwables.printStackTrace();
  44.           }
  45.       }
  46.        if (con != null){
  47.            try {
  48.                con.close();
  49.           } catch (SQLException throwables) {
  50.                throwables.printStackTrace();
  51.           }
  52.       }
  53.   }

方式2:

创建一个OracleCon类:

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. public class OracleCon {
  4.    public static Connection getConnection() {
  5.        String driver = "oracle.jdbc.driver.OracleDriver";
  6.        String url = "jdbc:oracle:thin:@127.0.0.1:1521:ORCLPDB";
  7.        String user = "c##daoen"; //用户
  8.        String password = "orcl"; //此用户密码
  9.        return getConnection(driver, url, user, password);
  10.   }
  11.    public static Connection getConnection(String driver, String url, String user, String password) {
  12.        Connection conn = null;
  13.        try {
  14.            Class.forName(driver); // 加载数据库驱动
  15.            conn = DriverManager.getConnection(url, user, password); // 获取数据库连接
  16.       } catch (Exception e) {
  17.            System.out.println(e);
  18.       }
  19.        System.out.println("连接成功");
  20.        return conn;
  21.   }
  22. }
新建dao层完成增删改查的案例:
  1. public class OracleDao {
  2.    //查询全部
  3.    public List<Emp> getEmpList(){
  4.        Connection con = OracleUtils.getConnection();
  5.        Statement state = null;
  6.        ResultSet rs = null;
  7.        String sql = "select * from c##EMP";
  8.        try {
  9.            state = con.createStatement();
  10.            rs = state.executeQuery(sql);
  11.            while (rs.next()){
  12.                int empId = rs.getInt(1);
  13.                String adminName = rs.getString(2);
  14.                String pwd = rs.getString(3);
  15.                Date birthday = rs.getDate(4);
  16.                System.out.println("编号:"+empId+" 姓名:"+adminName+" 密码"+pwd+" 日期:"+birthday);
  17.           }
  18.       } catch (SQLException throwables) {
  19.            throwables.printStackTrace();
  20.       }finally {
  21.            OracleUtils.close(con,state,rs);
  22.       }
  23.        return null;
  24.   }
  25.    //根据姓名和密码查询
  26.    public Emp getEmpByNameAndPwd(String userName,String pwd){
  27.        Connection con = OracleUtils.getConnection();
  28.        PreparedStatement ps = null;
  29.        ResultSet rs = null;
  30.        String sql = "select * from c##EMP where empName = ? and password = ?";
  31.        try {
  32.            ps = con.prepareStatement(sql);
  33.            ps.setString(1,userName);
  34.            ps.setString(2,pwd);
  35.            rs = ps.executeQuery();
  36.            if (rs.next()){
  37.                int empId = rs.getInt("empid");
  38.                String empName = rs.getString("empname");
  39.                String password = rs.getString("password");
  40.                Date birthday = rs.getDate("birthday");
  41.                System.out.println("编号:"+empId+" 姓名:"+empName+" 密码:"+password+" 日期:"+birthday);
  42.           }
  43.       } catch (SQLException throwables) {
  44.            throwables.printStackTrace();
  45.       }finally {
  46.            OracleUtils.close(con,ps,rs);
  47.       }
  48.        return null;
  49.   }
  50.    //删除
  51.    public Integer delEmp(Integer id){
  52.        Connection con = OracleUtils.getConnection();
  53.        PreparedStatement ps = null;
  54.        Integer rs = null;
  55.        String sql = "delete from c##EMP where empId = ?";
  56.        try {
  57.            ps = con.prepareStatement(sql);
  58.            ps.setInt(1,id);
  59.            rs = ps.executeUpdate();
  60.            if (rs > 0){
  61.                System.out.println("删除成功");
  62.           }else {
  63.                System.out.println("删除失败");
  64.           }
  65.       } catch (SQLException throwables) {
  66.            throwables.printStackTrace();
  67.       }finally {
  68.            OracleUtils.close(con,ps,null);
  69.       }
  70.        return 0;
  71.   }
  72.    //添加
  73.    public Integer addEmp(Emp emp){
  74.        Connection con = OracleUtils.getConnection();
  75.        PreparedStatement ps = null;
  76.        Integer rs = null;
  77.        String sql = "insert into c##EMP values(?,?,?,to_date(?,'yyyy-mm-dd'))";
  78.        try {
  79.            ps = con.prepareStatement(sql);
  80.            ps.setInt(1,emp.getEmpId());
  81.            ps.setString(2,emp.getEmpName());
  82.            ps.setString(3,emp.getPassword());
  83.            java.util.Date date = new java.util.Date(String.valueOf(emp.getBirthday()));
  84.            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  85.            String time = format.format(date);
  86.            ps.setString(4,time);
  87.            int rows = ps.executeUpdate();
  88.            if (rows > 0){
  89.                System.out.println("添加成功");
  90.           }else {
  91.                System.out.println("添加失败");
  92.           }
  93.       } catch (SQLException throwables) {
  94.            throwables.printStackTrace();
  95.       }finally {
  96.            OracleUtils.close(con,ps,null);
  97.       }
  98.        return 0;
  99.   }
  100.    //修改
  101.    public Integer updateEmp(Emp emp){
  102.        Connection con = OracleUtils.getConnection();
  103.        PreparedStatement ps = null;
  104.        Integer rs = null;
  105.        String sql = "update c##EMP set empname = ?,password = ?,birthday = to_date(?,'yyyy-mm-dd') where empId = ?";
  106.        try {
  107.            ps = con.prepareStatement(sql);
  108.            ps.setString(1,emp.getEmpName());
  109.            ps.setString(2,emp.getPassword());
  110.            java.util.Date date = new java.util.Date(String.valueOf(emp.getBirthday()));
  111.            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  112.            String time = dateFormat.format(date);
  113.            ps.setString(3,time);
  114.            ps.setInt(4,emp.getEmpId());
  115.            int rows = ps.executeUpdate();
  116.            if (rows > 0){
  117.                System.out.println("修改成功");
  118.           }else {
  119.                System.out.println("修改失败");
  120.           }
  121.       } catch (SQLException throwables) {
  122.            throwables.printStackTrace();
  123.       }finally {
  124.            OracleUtils.close(con,ps,null);
  125.       }
  126.        return 0;
  127.   }
  128. }
新建测试类测试:
  1. public class OracleTest {
  2.    public static void main(String[] args) {
  3.            //getEmpByNameAndPwd("孙道恩","111");
  4.           // deleteEmpById(2);
  5.       // getEmpList();
  6.        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  7.        Date date = null;
  8. //       try {
  9. //             date = dateFormat.parse("2012-09-12");
  10. //       } catch (ParseException e) {
  11. //           e.printStackTrace();
  12. //       }
  13. //       Emp emp = new Emp(5, "理想玩", "23df3", date);
  14. //       addEmp(emp);
  15.        try {
  16.          date = dateFormat.parse("2002-02-04");
  17.       } catch (ParseException e) {
  18.            e.printStackTrace();
  19.       }
  20.        Emp emp = new Emp(5, "普罗理想国", "88888888", date);
  21.        updateEmp(emp);
  22.   }
  23.    //查询全部
  24.    public static void   getEmpList(){
  25.        OracleDao oracleDao = new OracleDao();
  26.        List<Emp> empList = oracleDao.getEmpList();
  27.   }
  28.    //根据名字和密码查询
  29.    public static  void  getEmpByNameAndPwd(String name,String pwd){
  30.        OracleDao oracleDao = new OracleDao();
  31.        oracleDao.getEmpByNameAndPwd(name, pwd);
  32.   }
  33.    //根据id删除
  34.    public static void deleteEmpById(Integer id){
  35.        OracleDao oracleDao = new OracleDao();
  36.        oracleDao.delEmp(id);
  37.   }
  38.    //插入数据
  39.    public static void  addEmp(Emp emp){
  40.        OracleDao oracleDao = new OracleDao();
  41.        oracleDao.addEmp(emp);
  42.   }
  43.    //修改
  44.    public static void updateEmp(Emp emp){
  45.        OracleDao oracleDao = new OracleDao();
  46.        oracleDao.updateEmp(emp);
  47.   }
  48. }

jdbc连接MySQL数据库:

创建一个mysqlUtils类连接数据库:
  1. public class MysqlUtils {
  2.   public static Connection con = null;
  3.   public static Statement state = null;
  4.   public static ResultSet rs = null;
  5.   static {
  6.       try {
  7.           Class.forName("com.mysql.cj.jdbc.Driver");
  8.        } catch (ClassNotFoundException e) {
  9.           e.printStackTrace();
  10.        }
  11.    }
  12.   //连接数据库
  13.   public static Connection getCon() {
  14.       String url = "jdbc:mysql://localhost:3306/meitao?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false";
  15.       String username = "root";
  16.       String pwd = "root";
  17.       try {
  18.           con = DriverManager.getConnection(url, username, pwd);
  19.        } catch (SQLException throwables) {
  20.           throwables.printStackTrace();
  21.        }
  22.        System.out.println("连接成功");
  23.        return con;
  24.    }
  25.   //关闭连接
  26.   public static void close(Connection con,Statement state,ResultSet rs){
  27.       try {
  28.            if (rs != null){
  29.               rs.close();
  30.            }
  31.            if (state != null){
  32.               state.close();
  33.            }
  34.            if (con != null){
  35.               con.close();;
  36.            }
  37.        }catch (Exception e){
  38.           e.printStackTrace();
  39.        }
  40.    }
  41. }
编写mysqlDao层完成增删改查的案例:
  1. public class MysqlAdminDao {
  2.    //查询全部
  3.    public  List<Admins> getAdminList(){
  4.        Connection con = MysqlUtils.getCon();
  5.        PreparedStatement ps = null;
  6.        ResultSet rs = null;
  7.        String sql = "select * from admins";
  8.        try {
  9.            ps = con.prepareStatement(sql);
  10.            ResultSet resultSet = ps.executeQuery();
  11.            while (resultSet.next()){
  12.                int adminId = resultSet.getInt("adminId");
  13.                String adminName = resultSet.getString("adminName");
  14.                String pwd = resultSet.getString("pwd");
  15.                Date birthday = resultSet.getDate("birthday");
  16.                System.out.println("编号:"+adminId+" 姓名:"+adminName+" 密码:"+pwd+"生日:"+birthday);
  17.           }
  18.       } catch (SQLException throwables) {
  19.            throwables.printStackTrace();
  20.       }finally {
  21.            MysqlUtils.close(con,ps,rs);
  22.       }
  23.        return null;
  24.   }
  25.    //根据name和密码查询
  26.    public Admins getAdminsByIdAndName(String name,String pwd){
  27.        Connection con = MysqlUtils.getCon();
  28.        PreparedStatement ps= null;
  29.        ResultSet rs = null;
  30.        String sql = "select * from admins where adminname = ? and pwd = ?";
  31.        try {
  32.            ps = con.prepareStatement(sql);
  33.            ps.setString(1,name);
  34.            ps.setString(2,pwd);
  35.            ResultSet set = ps.executeQuery();
  36.            while (set.next()){
  37.                int adminId = set.getInt("adminId");
  38.                String adminName = set.getString("adminName");
  39.                String password = set.getString("pwd");
  40.                Date birthday = set.getDate("birthday");
  41.                System.out.println("编号:"+adminId+" 姓名:"+adminName+" 密码:"+password+"生日:"+birthday);
  42.           }
  43.       } catch (SQLException throwables) {
  44.            throwables.printStackTrace();
  45.       }finally {
  46.            MysqlUtils.close(con,ps,rs);
  47.       }
  48.        return null;
  49.   }
  50.    //根据id删除
  51.    public Integer delAdminById(Integer id){
  52.        Connection con = MysqlUtils.getCon();
  53.        PreparedStatement ps = null;
  54.        ResultSet rs = null;
  55.        String sql = "delete from admins where adminid = ?";
  56.        try {
  57.            ps = con.prepareStatement(sql);
  58.            ps.setInt(1,id);
  59.            int rows = ps.executeUpdate();
  60.            if (rows > 0){
  61.                System.out.println("删除成功");
  62.           }else {
  63.                System.out.println("删除失败");
  64.           }
  65.       } catch (SQLException throwables) {
  66.            throwables.printStackTrace();
  67.       }finally {
  68.            MysqlUtils.close(con,ps,rs);
  69.       }
  70.        return 0;
  71.   }
  72.    //添加数据
  73.    public Integer addAdmins(Admins admins){
  74.            Connection con = MysqlUtils.getCon();
  75.            PreparedStatement ps = null;
  76.            ResultSet rs = null;
  77.            String sql = "insert into admins values(?,?,?,?)";
  78.        try {
  79.            ps = con.prepareStatement(sql);
  80.            ps.setInt(1,admins.getAdminId());
  81.            ps.setString(2,admins.getAdminName());
  82.            ps.setString(3,admins.getPwd());
  83.            java.util.Date date = new java.util.Date(String.valueOf(admins.getBirthday()));
  84.            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  85.            String time = dateFormat.format(date);
  86.            ps.setString(4,time);
  87.            int rows = ps.executeUpdate();
  88.            if (rows > 0){
  89.                System.out.println("添加成功");
  90.           }else {
  91.                System.out.println("添加失败");
  92.           }
  93.       } catch (SQLException throwables) {
  94.            throwables.printStackTrace();
  95.       }finally {
  96.            MysqlUtils.close(con,ps,null);
  97.       }
  98.        return 0;
  99.   }
  100.    //修改数据
  101.    public Integer updateAdmins(Admins admins){
  102.        Connection con = MysqlUtils.getCon();
  103.        PreparedStatement ps = null;
  104.        ResultSet rs = null;
  105.        String sql = "update admins set adminname = ?,pwd = ?,birthday = ? where adminid = ?";
  106.        try {
  107.            ps = con.prepareStatement(sql);
  108.            ps.setString(1,admins.getAdminName());
  109.            ps.setString(2,admins.getPwd());
  110.            java.util.Date date = new java.util.Date(String.valueOf(admins.getBirthday()));
  111.            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  112.            String time = dateFormat.format(date);
  113.            ps.setString(3,time);
  114.            ps.setInt(4,admins.getAdminId());
  115.            int rows = ps.executeUpdate();
  116.            if (rows > 0){
  117.                System.out.println("修改成功");
  118.           }else {
  119.                System.out.println("修改失败");
  120.           }
  121.       } catch (SQLException throwables) {
  122.            throwables.printStackTrace();
  123.       }finally {
  124.            MysqlUtils.close(con,ps,null);
  125.       }
  126.        return 0;
  127.   }
  128. }
新建测试类进行测试:
  1. public class MysqlTest {
  2.    public static void main(String[] args) {
  3.      // getList();
  4.      // getAdminsByNameAndPwd("孙道恩","666");
  5.      // deleteById(3);
  6.        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  7.        Date date = null;
  8.        try {
  9.             date = dateFormat.parse("2015-02-04");
  10.       } catch (ParseException e) {
  11.            e.printStackTrace();
  12.       }
  13.        Admins admins = new Admins(3,"小金刚","sfd434",date);
  14.        //addAdmins(admins);
  15.        updateAdmins(admins);
  16.   }
  17.    //查找全部
  18.    public static void getList(){
  19.        MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
  20.        mysqlAdminDao.getAdminList();
  21.   }
  22.    //感觉name和pwd查找
  23.    public static void getAdminsByNameAndPwd(String name,String pwd){
  24.        MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
  25.        mysqlAdminDao.getAdminsByIdAndName(name, pwd);
  26.   }
  27.    //单个删除
  28.    public static void deleteById(Integer id){
  29.        MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
  30.        mysqlAdminDao.delAdminById(id);
  31.   }
  32.    //添加数据
  33.    public static void addAdmins(Admins admins){
  34.        MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
  35.        mysqlAdminDao.addAdmins(admins);
  36.   }
  37.    //修改数据
  38.    public static void updateAdmins(Admins admins){
  39.        MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
  40.        mysqlAdminDao.updateAdmins(admins);
  41.   }
  42. }

手写分页:

PagerUtil类:
  1. /**
  2. * 分页Bean
  3. *
  4. * @author sde
  5. */
  6. public class PagerUtil {
  7.    /**
  8.     * 当前页码数
  9.     */
  10.    private int currentPage = 1;
  11.    /**
  12.     * 每页显示记录条数, 默认为 2
  13.     */
  14.    private int sizePerPage = 2;
  15.    /**
  16.     * 总页数
  17.     */
  18.    private int totalPage;
  19.    /**
  20.     * 需要分页的长字符串
  21.     */
  22.    @SuppressWarnings("unchecked")
  23.    private List topicSelect;
  24.    public PagerUtil() {
  25.   }
  26.    /**
  27.     * 返回当前页的文本
  28.     *
  29.     * @return
  30.     */
  31.    @SuppressWarnings("unchecked")
  32.    public List getCurrentPagedText() {
  33.        try {
  34.            if (getCurrentPage() < getTotalPage()) {
  35.                return getTopicSelect().subList(
  36.                       (getCurrentPage() - 1) * getSizePerPage(), getCurrentPage() * getSizePerPage());
  37.           } else if (getTotalPage() > 0) {
  38.                return getTopicSelect().subList((getCurrentPage() - 1) * getSizePerPage(), getTopicSelect().size());
  39.           }
  40.       } catch (Exception e) {
  41.            e.printStackTrace();
  42.       }
  43.        return null;
  44.   }
  45.    /**
  46.     * @return Returns the 当前页码数.
  47.     */
  48.    public int getCurrentPage() {
  49.        if (currentPage <= 0)
  50.            currentPage = 1;
  51.        return currentPage;
  52.   }
  53.    /**
  54.     * 设置当前页码, 从 1 开始.
  55.     *
  56.     * @param currentPage The 当前页码数 to set.
  57.     */
  58.    public void setCurrentPage(int currentPage) {
  59.        if (currentPage <= 0) {
  60.            currentPage = 1;
  61.       }
  62.        this.currentPage = currentPage;
  63.   }
  64.    /**
  65.     * @return Returns the 总页码数, 如果没有数据, 就返回 1.
  66.     */
  67.    public int getTotalPage() {
  68.        if (getTopicSelect() == null)
  69.            totalPage = 0;
  70.        totalPage = (int) Math.ceil(1.0 * getTopicSelect().size()
  71.                / getSizePerPage()); // 总页面数
  72.        if (totalPage == 0)
  73.            totalPage = 1;
  74.        return totalPage;
  75.   }
  76.    /**
  77.     * @param totalPage The totalPage to set.
  78.     */
  79.    public void setTotalPage(int totalPage) {
  80.        this.totalPage = totalPage;
  81.   }
  82.    /**
  83.     * @return Returns the 每页显示行数.
  84.     */
  85.    public int getSizePerPage() {
  86.        return sizePerPage;
  87.   }
  88.    /**
  89.     * @param sizePerPage The 每页显示行数to set.
  90.     */
  91.    public void setSizePerPage(int sizePerPage) {
  92.        this.sizePerPage = sizePerPage;
  93.   }
  94.    /**
  95.     * @return Returns the 需要分页的文本.
  96.     */
  97.    @SuppressWarnings("unchecked")
  98.    public List getTopicSelect() {
  99.        return topicSelect;
  100.   }
  101.    @SuppressWarnings("unchecked")
  102.    public void setTopicSelect(List topicSelect) {
  103.        this.topicSelect = topicSelect;
  104.   }
  105. }
servlet:
  1. case "pageList":
  2.                //当前是第几页
  3.                int currentPage = 1;
  4.                //判断当前页码是否为空
  5.                if (req.getParameter("currentPage") != null){
  6.                    //不为空在页面中用户在请求分页
  7.                    currentPage = Integer.parseInt(req.getParameter("currentPage"));
  8.               }
  9.                    //一共多少页
  10.                    int maxPage;
  11.                    List<Employss> list = employeesService.getList();
  12.                System.out.println(list);
  13.                    //创建分页对象
  14.                    PagerUtil pager = new PagerUtil();
  15.                    //需要分页的文本
  16.                    pager.setTopicSelect(list);
  17.                    //设置每行显示的行数
  18.                    pager.setSizePerPage(3);
  19.                    //获取最大页数
  20.                    maxPage = pager.getTotalPage();
  21.                    //获取当前页
  22.                    pager.setCurrentPage(currentPage);
  23.                    //存值
  24.                System.out.println(pager.toString());
  25.                    req.setAttribute("lists",pager);
  26.                    req.getRequestDispatcher("list.jsp").forward(req,resp);
  27.                break;
前端展示和分页查询:
  1. <c:forEach var="user" items="${lists.currentPagedText}">
  2.            <tr>
  3.                <td>${user.empId}</td>
  4.                <td>${user.empName}</td>
  5.                <td>${user.birthday}</td>
  6.                <td>${user.address}</td>
  7.                <td>${user.tel}</td>
  8.                <td>${user.deptName}</td>
  9.                <td onclick="delById(${user.empId})" style="cursor: pointer">删除</td>
  10.                <td style="cursor: pointer" onclick="updateById(${user.empId})">修改</td>
  11.            </tr>
  12.        </c:forEach>
  13.            
  14.            
  15. <c:if test="${lists.currentPage==1}">
  16.        <c:out value="首页 上一页"></c:out>
  17.    </c:if>
  18.    <c:if test="${lists.currentPage != 1}">
  19.        <a href="loginServlet?method=pageList2&currentPage = 1">首页</a>
  20.        <a href="loginServlet?method=pageList2&currentPage=${lists.currentPage - 1}">上一页</a>
  21.    </c:if>
  22.    <c:if test="${lists.currentPage==lists.totalPage}">
  23.        <c:out value="下一页 尾页"></c:out>
  24.    </c:if>
  25.    <c:if test="${lists.currentPage != lists.totalPage}">
  26.        <a href="loginServlet?method=pageList2&currentPage=${lists.currentPage + 1}">下一页</a>
  27.        <a href="loginServlet?method=pageList2&currentPage=${lists.totalPage}">末页</a>
  28.    </c:if>
  29.    <span>每页显示 ${lists.sizePerPage} 条</span>
  30.    <span>第 ${lists.currentPage} 页</span>
  31.    <span>共 ${lists.totalPage} 页</span>            

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号