利用idea完成的第一个项目

Q1:数据库

create database if not exists StudentsDBs default charset utf8;
use StudentsDBs;
#Student(学生表)
drop database StudentsDBs;
create table Student
(
    Sid int primary key auto_increment,
    Sno char(3) not null comment '学号',
    Sname char(8) not null comment '学生姓名',
    Ssex char(2) not null comment '学生性别',
    Sbirthday datetime comment '学生出生年月',
    Class char(5) comment '学生所在班级',
    Course char(10) comment '课程'
);
#给学生表插入数据
insert into Student(Sno,Sname,Ssex,Sbirthday,Class,Course) vlaues('108','曾华','','1977-09-01','95033','语文');
insert into Student values
('108','曾华','','1977-09-01','95033','语文'),
('105','匡明','','1975-10-02','95031','数学'),
('107','王丽','','1976-01-23','95033','英语'),
('108','曾华','','1977-09-01','95033','数学'),
('105','匡明','','1975-10-02','95031','英语'),
('107','王丽','','1976-01-23','95033','数学'),
('101','李军','','1976-02-20','95033','语文'),
('109','王芳','','1975-02-10','95031','语文'),
('103','陆军','','1974-06-03','95031','语文'),
('101','李军','','1976-02-20','95033','数学'),
('109','王芳','','1975-02-10','95031','数学'),
('103','陆军','','1974-06-03','95031','数学'),
('101','李军','','1976-02-20','95033','导学率'),
('101','李军','','1976-02-20','95033','生物'),
('109','王芳','','1975-02-10','95031','高等教育'),
('109','王芳','','1975-02-10','95031','数学'),
('103','陆军','','1974-06-03','95031','人文'),
('101','李军','','1976-02-20','95033','英语'),
('101','李军','','1976-02-20','95033','物理'),
('109','王芳','','1975-02-10','95031','高等数学'),
('103','陆军','','1974-06-03','95031','人文素养');
select *from student;

Q2:vo

package vo;

import java.util.Date;

public class Students {
    int sid;
    String sno;
    String sname;
    String ssex;
    Date sbirthday;
    String classs;
    String course;
    public Students(){}
    public Students(int sid,String sno, String sname, String ssex, Date sbirthday, String classs,String course) {
        this.sid=sid;
        this.sno = sno;
        this.sname = sname;
        this.ssex = ssex;
        this.sbirthday = sbirthday;
        this.classs = classs;
        this.course=course;
    }
    public int getSid(){
        return  sid;
    }
    public void setSid(int sid){
        this.sid=sid;
    }
    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getSsex() {
        return ssex;
    }

    public void setSsex(String ssex) {
        this.ssex = ssex;
    }

    public Date getSbirthday() {
        return sbirthday;
    }

    public void setSbirthday(Date sbirthday) {
        this.sbirthday = sbirthday;
    }

    public String getClasss() {
        return classs;
    }

    public void setClasss(String classs) {
        this.classs = classs;
    }
    public String getCourse(){
        return  course;
    }
    public void setCourse(String course){
        this.course=course;
    }

    @Override
    public String toString() {
        return "Students{" +
                "sid=" + sid +
                ", sno='" + sno + '\'' +
                ", sname='" + sname + '\'' +
                ", ssex='" + ssex + '\'' +
                ", sbirthday=" + sbirthday +
                ", classs='" + classs + '\'' +
                ", course='" + course + '\'' +
                '}';
    }
}

Q3:dao

package dao;

import util.DBUtil;
import vo.Students;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Studentsdaoimpl {


    //计数

    public int getcount(){
        int count=0;

        String sql = "select count(*) from Student";
        ResultSet rs = DBUtil.executeQuery(sql);
        try {
            while(rs.next()) {
                count=Integer.parseInt(rs.getString(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
    //查询
   public static void main(String[] args) {
        Studentsdaoimpl s=new Studentsdaoimpl();
        /*List<Students> list=s.getMenuAllListPages(1,4);
        for(Students item:list){
            System.out.println(item.getSno()+","+item.getSname());
        }*/
        int count=s.getcount();
        System.out.println(count);
    }
    //删除
    public int deletes(int sid) {
        String sql="delete from Student where Sid=?";
        return DBUtil.executeUpdate(sql, new Object[] {sid});
    }
    //修改
    public int updates(String sname, String ssex, Date sbirthday, String classs, String course, int sid) {
        String sql="update Student set sname=?,ssex=?,sbirthday=?,Class=?,Course=? where sid=?";
        return DBUtil.executeUpdate(sql, new Object[] {sname,ssex,sbirthday,classs,course,sid});
    }
    //添加
    public int inserts(String sno,String sname, String ssex, Date sbirthday, String classs,String course) {
        String sql="insert into Student(Sno,Sname,Ssex,Sbirthday,Class,Course) values(?,?,?,?,?,?)";
        return DBUtil.executeUpdate(sql, new Object[] {sno,sname,ssex,sbirthday,classs,course});
    }
    /*查询*/
    public List<Students> getAllList() {
        String sql = "select * from Student";
        ResultSet rs =DBUtil.executeQuery(sql);
        List<Students> list = new ArrayList<Students>();
        Students model = null;
        try {
            while (rs.next()) {
                model = new Students();
                model.setSid(rs.getInt(1));
                model.setSno(rs.getString(2));
                model.setSname(rs.getString(3));
                model.setSsex(rs.getString(4));
                model.setSbirthday(rs.getDate(5));
                model.setClasss(rs.getString(6));
                model.setCourse(rs.getString(7));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }


    /*分页*/
    public List<Students> getMenuAllListPages(int page,int limit){
        int start=(page-1)*limit;
        String sql="select *from Student limit "+start+","+limit;
        ResultSet rs =DBUtil.executeQuery(sql);
        List<Students> list = new ArrayList<Students>();
        Students model = null;
        try{
            while (rs.next()){
                model=new Students();
                model.setSid(rs.getInt(1));
                model.setSno(rs.getString(2));
                model.setSname(rs.getString(3));
                model.setSsex(rs.getString(4));
                model.setSbirthday(rs.getDate(5));
                model.setClasss(rs.getString(6));
                model.setCourse(rs.getString(7));
                list.add(model);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }

        return list;
    }
}

 

Q4:dao测试

package dao;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import vo.Students;

import java.util.List;


public class StudentsdaoimplTest {
    public static Studentsdaoimpl sd=new Studentsdaoimpl();
    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void getcount() {
        int a=sd.getcount();
        System.out.println(a);
    }

    @Test
    public void main() {
    }

    @Test
    public void deletes() {
    }

    @Test
    public void updates() {
    }

    @Test
    public void inserts() {
    }

    @Test
    public void getAllList() {
        List<Students> list=sd.getAllList();
        System.out.println(list.toString());
    }

    @Test
    public void getMenuAllListPages() {
        List<Students> list=sd.getMenuAllListPages(1,5);
        System.out.println(list.toString());
    }
}

 

Q5:bo

package bo;

import dao.Studentsdaoimpl;
import vo.Students;

import java.util.Date;
import java.util.List;

public class Studentsboimpl {

   /*查询*/
   Studentsdaoimpl sd=new Studentsdaoimpl();
    public List<Students> getAllList(){
        return sd.getAllList();
    }
    /*计数*/
    public int getcount(){
        return  sd.getcount();
    }
    /*分页*/
    public List<Students> getMenuAllListPages(int page,int limit){
        return  sd.getMenuAllListPages(page,limit);
    }
   public int updates(String sname, String ssex, Date sbirthday, String classs, String course,int sid){
        return sd.updates(sname,ssex,sbirthday,classs,course,sid);
    }
    public int inserts(String sno, String sname, String ssex, Date sbirthday, String classs,String course){
        return  sd.inserts(sno,sname,ssex,sbirthday,classs,course);
    }
    public int deletes(int sid){
        return  sd.deletes(sid);
    }
}

 

Q6:bo测试

package bo;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import vo.Students;

import java.util.List;

public class StudentsboimplTest {
    public static Studentsboimpl sb=new Studentsboimpl();
    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void getAllList() {
        List<Students> list=sb.getAllList();
        System.out.println(list.toString());
    }

    @Test
    public void getcount() {
        int a=sb.getcount();
        System.out.println(a);
    }

    @Test
    public void getMenuAllListPages() {
        List<Students> list=sb.getMenuAllListPages(1,5);
        System.out.println(list.toString());
    }

    @Test
    public void updates() {
    }

    @Test
    public void inserts() {
    }

    @Test
    public void deletes() {
    }
}

 

Q7:baseController

package action;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet(name = "actionBaseController")
public class actionBaseController extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String action=request.getParameter("action");
        if(action!=null) {
            //在当前Servlet实例中根据action找到方法信息
            try {
                Method method = getClass().getDeclaredMethod(action, HttpServletRequest.class,
                        HttpServletResponse.class);
                if (method != null) {
                    // 在当前实例上调用方法method,指定参数request,response
                    try {
                        method.invoke(this, request, response);
                    } catch (IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        System.out.println("安全权限异常,一般来说,是由于java在反射时调用了private方法所导致的。如"
                                + "果是这种情况的话,要把反射pirvate的方向设置成public,再调用");
                        //e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        System.out.println("此异常表明向方法传递了一个不合法或不正确的参数");
                        //e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        // TODO Auto-generated catch block
                        System.out.println("是一种包装由调用方法或构造方法所抛出异常的受查异常");
                        e.printStackTrace();
                    }
                }
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                response.getWriter().write("您请求的action不存在");
                //e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                System.out.println("是安全异常的意思。你再仔细检查和安全设置相关的选项是否都设置正确。");
                //e.printStackTrace();
            }

        }else {
            response.getWriter().write("请指定参数action。");
        }
    }
}

 

Q8:servlet(继承basecontroller)

package action;

import bo.Studentsboimpl;
import jsonUtil.JsonUtils;
import vo.Students;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet(name = "actionStudents")
public class actionStudents extends actionBaseController {
    /**计数*/
    public void counts(HttpServletRequest request, HttpServletResponse response){
        Studentsboimpl si=new Studentsboimpl();
        String count=si.getcount()+"";
        try {
            response.getWriter().print("{\"counts\":"+count+"}");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 查询数据
     * */
    public void select(HttpServletRequest request, HttpServletResponse response){
        Studentsboimpl sb=new Studentsboimpl();
        List<Students> list=sb.getAllList();
        List<Students> lists=new ArrayList<Students>();
        for(Students item:list){
            lists.add(new Students(item.getSid(),item.getSno(), item.getSname(),item.getSsex(),item.getSbirthday(),item.getClasss(),
                    item.getCourse()));
        }
        try {
            System.out.println(JsonUtils.toJson(lists));
            response.getWriter().println(JsonUtils.toJson(lists));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
    * 分页
    * */
    public void selectpage(HttpServletRequest request, HttpServletResponse response){
        Studentsboimpl sb=new Studentsboimpl();
        int page=Integer.parseInt(request.getParameter("page"));
        int limit=Integer.parseInt(request.getParameter("limit"));
        List<Students> list=sb.getMenuAllListPages(page,limit);
        List<Students> lists=new ArrayList<Students>();
        for(Students item:list){
            lists.add(new Students(item.getSid(),item.getSno(), item.getSname(),item.getSsex(),item.getSbirthday(),item.getClasss()
            ,item.getCourse()));
        }
        try {
            System.out.println(JsonUtils.toJson(lists));
            response.getWriter().println(JsonUtils.toJson(lists));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 添加数据
     * */
    public void insert(HttpServletRequest request, HttpServletResponse response){
        Studentsboimpl sb=new Studentsboimpl();
        String Sno=request.getParameter("Sno");
        String Sname=request.getParameter("Sname");
        String Ssex=request.getParameter("Ssex");
        String Sbirthday=request.getParameter("Sbirthday");
        Date date=null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(Sbirthday);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        java.sql.Timestamp datetime = new java.sql.Timestamp(date.getTime());
        String Classs=request.getParameter("Classs");
        String course=request.getParameter("Course");
        int a=sb.inserts(Sno,Sname,Ssex,datetime,Classs,course);
        if(a>0){
            try {
                response.getWriter().print("{\"msg\":\"添加成功\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 删除数据
     * */
    public void deletes(HttpServletRequest request, HttpServletResponse response){
        Studentsboimpl sb=new Studentsboimpl();
        int Sno=Integer.parseInt(request.getParameter("Sno"));
        int a=sb.deletes(Sno);
        if(a>0){
            try {
                response.getWriter().print("{\"msg\":\"删除成功!\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 修改数据
     * */
    public void updates(HttpServletRequest request, HttpServletResponse response){
        Studentsboimpl sb=new Studentsboimpl();
        String Sname=request.getParameter("Sname");
        String Ssex=request.getParameter("Ssex");
        String Sbirthday=request.getParameter("Sbirthday");
        Date date=null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(Sbirthday);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        java.sql.Timestamp datetime = new java.sql.Timestamp(date.getTime());
        String Classs=request.getParameter("Classs");
        String course= request.getParameter("Course");
        int Sno=Integer.parseInt(request.getParameter("Sno"));
        int a=sb.updates(Sname,Ssex,datetime,Classs,course,Sno);
        if(a>0){
            try {
                response.getWriter().print("{\"msg\":\"修改成功\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

Q9:html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="js/layui/css/layui.css">
</head>
<style>
    table,th,td{
        border: 1px solid red;
        border-collapse: collapse;
        text-align: center;
    }
    table{
        width: 100%;
        box-shadow: 3px 3px 3px blue;
    }
    th,td{
        height: 30px;
    }
    input[type=button]{
        background: yellowgreen;
        color: white;
    }
    thead tr{
        background: red;
        color: white;
    }
</style>
<body>
    <script src="js/jquery-1.11.3.js"></script>
    <script src="js/layui/layui.all.js"></script>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>自定义分页展示框</legend>
    </fieldset>
    <div id="demo11"></div>
    <table>
        <thead>
        <tr>
            <th>编号</th>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>班级</th>
            <th>课程</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <fieldset>
        <legend>添加</legend>
        <p>
            <label for="Sno">学号</label>
            <input type="text" id="Sno" name="Sno" placeholder="请输入学号" />
        </p>
        <p>
            <label for="Sname">姓名</label>
            <input type="text" id="Sname" name="Sname" placeholder="请输入姓名"/>
        </p>
        <p>
            <label>性别</label><input type="radio"  name="sex" value="男" id="man"/><input type="radio"  name="sex" value="女" id="woman"/>
        </p>
        <p>
            <label for="Sbirthday">日期</label>
            <input type="date" id="Sbirthday" name="Sbirthday"/>
        </p>
        <p>
            <label>班级</label>
            <select id="sel1">
                <option value ="95033">95033</option>
                <option value ="95031">95031</option>
            </select>
        </p>
        <p>
            <label>课程</label>
            <select id="sel2">
                <option value ="语文">语文</option>
                <option value ="数学">数学</option>
                <option value ="英语">英语</option>
                <option value ="数学">物理</option>
                <option value ="物理">化学</option>
                <option value ="生物">生物</option>
                <option value ="人文素养">人文素养</option>
                <option value ="高等数学">高等数学</option>
            </select>
        </p>
        <p>
            <input type="button" value="添加" id="btnadd"/>
            <input type="button" value="修改" id="btnupdate"/>
        </p>
    </fieldset>
    <script>
        var number="";
        $.ajax({
             type:'post',
             url:'actionStudents?action=counts',
             async:false,
             success:function (data) {
                 number=data.counts;
             }
         });
    var pages="";var limits="";
    layui.use(['laypage', 'layer'], function(){
        var laypage = layui.laypage
            ,layer = layui.layer;
        //自定义每页条数的选择项
        function m() {
            /**/
            laypage.render({
                elem: 'demo11'
                ,limit: 5
                ,count: number
                ,async:false
                ,curr:pages
                ,jump:function (objs){
                    pages=objs.curr;
                    limits=objs.limit;
                    /**/
                    $("table tbody tr").remove();
                    $.ajax({
                        type:'post',
                        data:{page:pages ,limit:limits},
                        url:'actionStudents?action=selectpage',
                        success:function (data) {
                            $.each(data,function (i,obj) {
                                var tr=$("<tr/>");
                                (tr).append($("<td/>").html(obj.sid))
                                    .append($("<td/>").html(obj.sno)).append($("<td/>").html(obj.sname))
                                    .append($("<td/>").html(obj.ssex)).append($("<td/>").html(obj.sbirthday))
                                    .append($("<td/>").html(obj.classs)).append($("<td/>").html(obj.course))
                                    .append($("<td/>")
                                        .append($("<input type='button' value='删除' id='btnDel'/>").data("obj",obj.sid))
                                        .append($("<input type='button' value='编辑' id='btnEdit'/>").data("obj",obj))

                                    ).appendTo($("table tbody"));
                            })
                        }
                    });
                    /**/
                }
            });
            /**/
        };


        /**/
        var app={
            /*查询*/
            updaid:"",
            select:function(){

            },
            /*编辑*/
            edits:function(obj){
                $("#Sno").val(obj.sno);$("#Sname").val(obj.sname);
                /*$("input[type='radio']:checked").val(obj.ssex);*/
                $("#Sbirthday").val(obj.sbirthday);
                $("#sel1").val(obj.classs);
                $("#sel2").val(obj.course);
                if(obj.ssex==""){
                    $("#man").prop("checked","true");
                }else {
                    $("#woman").prop("checked","true");
                }
            },
            /*修改*/
            updat:function(){
                if(confirm("是否要修改?")){
                    var Sname=$("#Sname").val();
                    var Ssex=$("input[type='radio']:checked").val();
                    var Sbirthday=$("#Sbirthday").val();
                    var Classs=$("#sel1").val();
                    var Course=$("#sel2").val();
                    /*alert(Sname+Ssex+Sbirthday+Classs+app.updaid)*/;
                    $.ajax({
                        type:'post',
                        data:{Sname:Sname,Ssex:Ssex,Sbirthday:Sbirthday,Classs:Classs,Course:Course,Sno:app.updaid},
                        url:'actionStudents?action=updates',
                        success:function (data) {
                            alert(data.msg);
                            m();
                        }
                    });
                }
            },
            /*删除*/
            deletes:function(obj){
                if(confirm("是否要删除?")){
                    var Sno=obj;
                    $.ajax({
                        type:'post',
                        data:{Sno:Sno},
                        url:'actionStudents?action=deletes',
                        success:function (data) {
                            alert(data.msg);
                            m();
                        }
                    });
                }
            },
            /*添加*/
            inserts:function(){
                var Sno=$("#Sno").val();var Sname=$("#Sname").val();
                var Ssex=$("input[type='radio']:checked").val();
                var Sbirthday=$("#Sbirthday").val();
                var Classs=$("#sel1").val();
                var Course=$("#sel2").val();
                $.ajax({
                    type:'post',
                    data:{Sno:Sno,Sname:Sname,Ssex:Ssex,Sbirthday:Sbirthday,Classs:Classs,Course:Course},
                    url:'actionStudents?action=insert',
                    success:function (data) {
                        alert(data.msg);
                        m();
                    }
                });
            },
            /*一些绑定事件*/
            clicks:function(){
                /*添加事件*/
                $("#btnadd").click(function () {
                    app.inserts();
                });
                $("table tbody").on("click","#btnEdit",function () {
                    var Sno=$(this).data("obj");
                    app.updaid=Sno.sid;
                    app.edits(Sno);
                });
                $("table tbody").on("click","#btnDel",function () {
                    var Sno=$(this).data("obj");
                    app.deletes(Sno);
                }),
                    /*修改*/
                    $("#btnupdate").click(function () {
                        app.updat();
                    })
            },
            /*初始化方法*/
            init:function () {
                m();
                app.clicks();
            }
        };
        app.init();
        /**/
    });
    </script>
</body>
</html>

Q10:DBUtil

package util;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DBUtil {
    //连接对象
    //Statement 命令对象
    //打开连接
    //关闭连接
    //得到一个连接对象
    //查询(有参,无参)
    //修改(有参,无参)

    static Connection conn = null;
    static Statement stmt = null;
    //驱动,服务器地址,登录用户名,密码    
    /*static String DBDRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static String DBURL="jdbc:sqlserver://localhost:1433;DatabaseName=login";
    static String DBUSER="sa";
    static String DBPWD="caoyu3520563253";*/
    static String DBDRIVER;
    static String DBURL;
    static String DBUSER;
    static String DBPWD;

    static {
        //先创建资源文件,扩展名为.properties
        //内容是以:dbuser=sa  格式
        Properties prop = new Properties();//先获取资源对象
        try {
            prop.load(Thread.currentThread().getContextClassLoader().
                    getResourceAsStream("resources/dbconfig.properties"));
            DBDRIVER = prop.getProperty("DBDRIVER");
            DBURL = prop.getProperty("DBURL");
            DBUSER = prop.getProperty("DBUSER");
            DBPWD = prop.getProperty("DBPWD");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //打开连接
    public static void open() {
        //加载驱动
        try {
            Class.forName(DBDRIVER);
            conn=DriverManager.getConnection(DBURL,DBUSER,DBPWD);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //关闭连接
    public static void close() {
        try {
            if(stmt!=null && stmt.isClosed())
                stmt.close();
            if(conn!=null && !conn.isClosed())
                conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //得到一个连接对象,当用户使用DBUtil无法解决个性问题时
    //可以通过本方法获得连接对象
    public static Connection getConnection() {
        try {
            if(conn==null ||conn.isClosed())
                open();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //executeQuery
    //executeUpdate
    //execute
    //获得查询的数据集
    //不带参数的查询
    //select * from student where name='' and sex=''
    public static ResultSet executeQuery(String sql) {
        try {
            open();//保证连接是成功的
            stmt = conn.createStatement();
            return stmt.executeQuery(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    //修改表格内容
    public static int executeUpdate(String sql) {
        int result = 0;
        try {
            open();//保证连接是成功的
            stmt = conn.createStatement();
            result = stmt.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            close();
        }
        return result;
    }
    //如果执行的查询或存储过程,会返回多个数据集,或多个执行成功记录数
    //可以调用本方法,返回的结果,
    //是一个List<ResultSet>或List<Integer>集合
    public static Object execute(String sql) {
        boolean b=false;
        try {
            open();//保证连接是成功的
            stmt = conn.createStatement();
            b = stmt.execute(sql);
            //true,执行的是一个查询语句,我们可以得到一个数据集
            //false,执行的是一个修改语句,我们可以得到一个执行成功的记录数
            if(b){
                return stmt.getResultSet();
            }
            else {
                return stmt.getUpdateCount();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(!b) {
                close();
            }
        }
        return null;
    }

    //
    //select * from student where name=? and sex=?
    //带参数的查询,只有输入参数
    public static ResultSet executeQuery(String sql,Object[] in) {
        try {
            open();//保证连接是成功的
            PreparedStatement pst = conn.prepareStatement(sql);
            for(int i=0;i<in.length;i++)
                pst.setObject(i+1, in[i]);
            stmt = pst;//只是为了关闭命令对象pst
            return pst.executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    //带参数修改,只有输入参数
    public static int executeUpdate(String sql,Object[] in) {
        try {
            open();//保证连接是成功的
            PreparedStatement pst = conn.prepareStatement(sql);
            for(int i=0;i<in.length;i++)
                pst.setObject(i+1, in[i]);
            stmt = pst;//只是为了关闭命令对象pst
            return pst.executeUpdate();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            //e.printStackTrace();
        }finally {
            close();
        }
        return 0;
    }
    public static Object execute(String sql,Object[] in) {
        boolean b=false;
        try {
            open();//保证连接是成功的
            PreparedStatement pst = conn.prepareStatement(sql);
            for(int i=0;i<in.length;i++)
                pst.setObject(i+1, in[i]);
            b = pst.execute();
            //true,执行的是一个查询语句,我们可以得到一个数据集
            //false,执行的是一个修改语句,我们可以得到一个执行成功的记录数
            if(b){
                System.out.println("----");
                /*List<ResultSet> list = new ArrayList<ResultSet>();
                list.add(pst.getResultSet());
                while(pst.getMoreResults()) {
                    list.add(pst.getResultSet());
                }*/
                return pst.getResultSet();
            }
            else {
                System.out.println("****");
                List<Integer> list = new ArrayList<Integer>();
                list.add(pst.getUpdateCount());
                while(pst.getMoreResults()) {
                    list.add(pst.getUpdateCount());
                }
                return list;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(!b) {
                System.out.println("====");
                close();
            }
        }
        return null;
    }
    //调用存储过程  proc_Insert(?,?,?)
    public static Object executeProcedure(String procName,Object[] in) {
        open();
        try {
            procName = "{call "+procName+"(";
            String link="";
            for(int i=0;i<in.length;i++) {
                procName+=link+"?";
                link=",";
            }
            procName+=")}";
            CallableStatement cstmt = conn.prepareCall(procName);
            for(int i=0;i<in.length;i++) {
                cstmt.setObject(i+1, in[i]);
            }
            if(cstmt.execute())
            {
                return cstmt.getResultSet();
            }
            else {
                return cstmt.getUpdateCount();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }


    /*
     * 调用存储过程,并有输出参数
     * @procName ,存储过程名称:proc_Insert(?,?)
     * @in ,输入参数集合
     * @output,输出参数集合
     * @type,输出参数类型集合
     * */
    public static Object executeOutputProcedure(String procName,
                                                Object[] in,Object[] output,int[] type){
        Object result = null;
        try {
            CallableStatement cstmt = conn.prepareCall("{call "+procName+"}");
            //设置存储过程的参数值
            int i=0;
            for(;i<in.length;i++){//设置输入参数
                cstmt.setObject(i+1, in[i]);
                //print(i+1);
            }
            int len = output.length+i;
            for(;i<len;i++){//设置输出参数
                cstmt.registerOutParameter(i+1,type[i-in.length]);
                //print(i+1);
            }
            boolean b = cstmt.execute();
            //获取输出参数的值
            for(i=in.length;i<output.length+in.length;i++)
                output[i-in.length] = cstmt.getObject(i+1);
            if(b) {
                result = cstmt.getResultSet();
            }
            else {
                result = cstmt.getUpdateCount();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    //调用存储过程查询出所有的值
    public static Object executeProcedures(String procName) {
        open();
        try {
            procName = "{call "+procName+"}";
            CallableStatement cstmt = conn.prepareCall(procName);
            if(cstmt.execute())
            {
                return cstmt.getResultSet();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
View Code

 

Q11:配置文件

DBDRIVER=com.mysql.jdbc.Driver
DBURL=jdbc:mysql://localhost:3306/StudentsDBs?serverTimezone=GMT%2B8
DBUSER=root
DBPWD=

 

Q12:json装换

package jsonUtil;

import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
    /**
     *  序列化成json
     * */
    public static String toJson(Object obj) {
        // 对象映射器
        ObjectMapper mapper = new ObjectMapper();
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss");
        //mapper.setDateFormat(sdf);

        String result = null;
        // 序列化user对象为json字符串
        try {
            result = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 反序列化成对象
     * */
    public static <T> T toObject(String json,Class<T> valueType) {
        //对象映射器
        ObjectMapper mapper=new ObjectMapper();
        T result=null;
        try {
            result=mapper.readValue(json,valueType);

        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

 

Q13:展示

 

posted @ 2018-09-06 20:26  zywds  阅读(375)  评论(0编辑  收藏  举报