【问题标题】:complex query function - how to make it prepared?复杂的查询功能——如何准备?
【发布时间】:2012-04-24 16:58:34
【问题描述】:

我正在处理用户输入并为页面创建了一个过滤器。它正在工作,但我知道我直接查询数据库。

可以优化此查询以作为准备好的查询工作吗?我决定在开始输入一堆 if-else 语句之前咨询专业人士。

public ArrayList<data.exam> getAllExamsList(
        String course, String building, String room,
        String capacity, String numberenrolled, String day,
        String starttime, String endtime, String callnumber,
        String department, String instructor, boolean coursebox,
        boolean buildingbox, boolean roombox, boolean capacitybox,
        boolean numberenrolledbox, boolean daybox, boolean startbox,
        boolean endbox, boolean callbox, boolean departmentbox,
        boolean instructorbox, String starttimesearchfrom, String starttimesearchto,
        String endtimesearchfrom, String endtimesearchto) throws SQLException {

    String findstarttimesearchfrom = starttimesearchfrom.equals("ALL") ? "" : "  AND `Start Time`>=time('" + starttimesearchfrom + "')";
    String findstarttimesearchto = starttimesearchto.equals("ALL") ? "" : "  AND `Start Time`<=time('" + starttimesearchto + "')";
    String findendtimesearchfrom = endtimesearchfrom.equals("ALL") ? "" : "  AND `End Time`>=time('" + endtimesearchfrom + "')";
    String findendtimesearchto = endtimesearchto.equals("ALL") ? "" : "  AND `End Time`<=time('" + endtimesearchto + "')";

    int totalOutPuts = 0; //how many checkboxes are checked

    boolean checks[] = new boolean[]{coursebox, buildingbox, roombox,
        capacitybox, numberenrolledbox, daybox, startbox, endbox,
        callbox, departmentbox, instructorbox};

    for (boolean check : checks) {
        if (check) {
            totalOutPuts++; //adding to checked boxes count
        }
    }

    String groupBy = " Group by "; //create a Group by statement for query
    for (int i = 1; i < totalOutPuts; i++) {
        groupBy += i + ", ";
    }
    groupBy += totalOutPuts + ""; //adding the last element to Group by w/o comma

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    Connection con = null;
    Statement stmnt = null;
    ResultSet displayString = null;
    ArrayList<data.exam> exams = new ArrayList<data.exam>(); //will bre returned back with list of exams

    String showcoursebox = coursebox == true ? "`Course Number`" : "";
    showcoursebox += (coursebox && (buildingbox || roombox || capacitybox || numberenrolledbox || daybox || startbox || endbox || callbox || departmentbox || instructorbox)) ? ", " : "";

    String showbuildingbox = buildingbox == true ? "Building" : "";
    showbuildingbox += (buildingbox && (roombox || capacitybox || numberenrolledbox || daybox || startbox || endbox || callbox || departmentbox || instructorbox)) ? ", " : "";

    String showroombox = roombox == true ? "`Room Number`" : "";
    showroombox += (roombox && (capacitybox || numberenrolledbox || daybox || startbox || endbox || callbox || departmentbox || instructorbox)) ? ", " : "";

    String showcapacitybox = capacitybox == true ? "`Room Capacity`" : "";
    showcapacitybox += (capacitybox && (numberenrolledbox || daybox || startbox || endbox || callbox || departmentbox || instructorbox)) ? ", " : "";

    String shownumberenrolled = numberenrolledbox == true ? "`Number Enrolled`" : "";
    shownumberenrolled += (numberenrolledbox && (daybox || startbox || endbox || callbox || departmentbox || instructorbox)) ? ", " : "";

    String showdaybox = daybox == true ? "`Exam Day`" : "";
    showdaybox += (daybox && (startbox || endbox || callbox || departmentbox || instructorbox)) ? ", " : "";

    String showstartbox = startbox == true ? "`Start Time`" : "";
    showstartbox += (startbox && (endbox || callbox || departmentbox || instructorbox)) ? ", " : "";

    String showendbox = endbox == true ? "`End Time`" : "";
    showendbox += (endbox && (callbox || departmentbox || instructorbox)) ? ", " : "";

    String showcallbox = callbox == true ? "`Call Number`" : "";
    showcallbox += (callbox && (departmentbox || instructorbox)) ? ", " : "";

    String showdepartmentbox = departmentbox == true ? "Department" : "";
    showdepartmentbox += (departmentbox && (instructorbox)) ? ", " : "";

    String showinstructorbox = instructorbox == true ? "Instructor" : "";

    String findCourse = course.equals("ALL") ? "" : " AND `Course Number`=" + course;
    String findBuilding = building.equals("ALL") ? "" : " AND `Building`='" + building + "'";
    String findRoom = room.equals("ALL") ? "" : " AND `Room Number`='" + room + "'";
    String findCapacity = capacity.equals("ALL") ? "" : " AND `Room Capacity`='" + capacity + "'";
    String findNumberEnrolled = numberenrolled.equals("ALL") ? "" : " AND `Number Enrolled`='" + numberenrolled + "'";
    String findDay = day.equals("ALL") ? "" : " AND `Exam Day` LIKE '%" + day.toLowerCase() + "%'";
    String findStarttime = starttime.equals("ALL") ? "" : " AND `Start Time`=time('" + starttime + "')";
    String findEndtime = endtime.equals("ALL") ? "" : " AND `End Time`=time('" + endtime + "')";
    String findCall = callnumber.equals("ALL") ? "" : " AND `Call Number`=" + callnumber;
    String findDepartment = department.equals("ALL") ? "" : " AND `Department`='" + department + "'";
    String findInstructor = instructor.equals("ALL") ? "" : " AND `Instructor`='" + instructor + "'";

    String query = "select "
            + showcoursebox
            + showbuildingbox
            + showroombox
            + showcapacitybox
            + shownumberenrolled
            + showdaybox
            + showstartbox
            + showendbox
            + showcallbox
            + showdepartmentbox
            + showinstructorbox
            + " from"
            + "    (select "
            + "        exam_schedules.course_id as id,"
            + "            rooms.number as 'Room Number',"
            + "            rooms.building as Building,"
            + "            rooms.capacity as 'Room Capacity',"
            + "            day as 'Exam Day',"
            + "            start_time as 'Start Time',"
            + "            end_time as 'End Time'"
            + "    from"
            + "        exam_schedules, rooms"
            + "    where"
            + "        exam_schedules.room_id = rooms.id) r1,"
            + "    (select "
            + "        courses.id,"
            + "            courses.number_enrolled as 'Number Enrolled',"
            + "            courses.call_number as 'Call Number',"
            + "            courses.course_number as 'Course Number',"
            + "            departments.department_code as Department,"
            + "            instructors.full_name as Instructor"
            + "    from"
            + "        courses, departments, instructors"
            + "    where"
            + "        courses.department_id = departments.id and courses.instructor_id = instructors.id) r2"
            + " where"
            + "    r2.id = r1.id "
            + findCourse + findBuilding + findRoom + findCapacity
            + findNumberEnrolled + findDay + findStarttime + findEndtime
            + findCall + findDepartment + findInstructor
            + findstarttimesearchfrom
            + findstarttimesearchto
            + findendtimesearchfrom
            + findendtimesearchto
            + groupBy;

    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con = (Connection) DriverManager.getConnection(DBurl, user, password);
        stmnt = (Statement) con.createStatement();
        String readTopic = query;
        displayString = stmnt.executeQuery(readTopic);
        while (displayString.next()) {
            try {

                String courseObj = "",
                        buildingObj = "",
                        roomObj = "",
                        capacityObj = "",
                        numberenrolledObj = "",
                        dayObj = "",
                        starttimeObj = "",
                        endtimeObj = "",
                        callnumberObj = "",
                        departmentObj = "",
                        instructorObj = "";

                courseObj = coursebox == true ? displayString.getString("Course Number") : "";
                buildingObj = buildingbox == true ? displayString.getString("Building") : "";
                roomObj = roombox == true ? displayString.getString("Room Number") : "";
                capacityObj = capacitybox == true ? displayString.getString("Room Capacity") : "";
                numberenrolledObj = numberenrolledbox == true ? displayString.getString("Number Enrolled") : "";
                dayObj = daybox == true ? displayString.getString("Exam Day") : "";
                starttimeObj = startbox == true ? displayString.getString("Start Time") : "";
                endtimeObj = endbox == true ? displayString.getString("End Time") : "";
                callnumberObj = callbox == true ? displayString.getString("Call Number") : "";
                departmentObj = departmentbox == true ? displayString.getString("Department") : "";
                instructorObj = instructorbox == true ? displayString.getString("Instructor") : "";

                data.exam O = new data.exam(courseObj, buildingObj, roomObj, capacityObj,
                        numberenrolledObj, dayObj, starttimeObj, endtimeObj, callnumberObj,
                        departmentObj, instructorObj);

                exams.add(O);
            } catch (Exception E) {
            }
        }
        displayString.close();
        con.close();
    } catch (Exception e) {

        if (con != null) {
            con.close();
        }
        if (stmnt != null) {
            stmnt.close();
        }
        if (displayString != null) {
            displayString.close();
        }
        e.printStackTrace(pw);
    }

    return exams;
}

【问题讨论】:

  • 只是一个路过的评论——你不需要在三元运算符中检查 == true (例如 roombox == true),只需声明 roombox ? ...它使阅读更容易。

标签: java mysql sql jsp prepared-statement


【解决方案1】:

有几件事可以帮助您:

  • 创建一个可以传递给此 getAllExamsList 方法的对象。这将组织您的数据模型并缩短庞大的参数列表。
public Exam{
    private String course;
    private String building;
    private String room;
    //additional variabled you have in the getAllExamsList parameter list
    public Exam(String course, String building, String room){
        this.course=course;
        this.building=building;
        this.room=room;
    }
    //additional getters and setters
}
  • 看看这个tutorial准备好的语句

【讨论】:

    猜你喜欢
    • 2019-12-30
    • 2012-06-02
    • 2012-11-23
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多