PL / SQL / Java - SQL为循环选择if语句和列表

时间:2012-03-15 13:04:01

标签: java sql

就在那时,我已经创建了一个应用程序来为路线上的学生创建新的预订。 这应该使用包含这些时间的数据库来计算碰撞时间。

e.g。学生在12:00检查考试,程序将检查该时间周围的任何其他测试,然后检查碰撞时间,如果发生碰撞,它将在开始时间后加5分钟再试一次。这就是我的目标。

我知道这远非完美或正确,但这就是我在这里的原因。

预订课程

public class Booking
{
    private int bookingId;
    private String route;
    private int startTime;
    private String bookingDate;

    public Booking()
    {
        bookingId = 0000;
        route = "No Route Entered";
        startTime = 0000;
        bookingDate = "No Date entered";
    }

    public int getBookingId()
    {
        return bookingId;
    }

    public String getRoute()
    {
        return route;
    }

    public int getStartTime()
    {
        return startTime;
    }

    public String getBookingDate()
    {
        return bookingDate;
    }

    public void setBookingId(int bookingId)
    {
        this.bookingId = bookingId;
    }

    public void setRoute(String route)
    {
        this.route = route;
    }

    public void setStartTime(int startTime)
    {
        this.startTime = startTime;
    }

    public void setBookingDate(String bookingDate)
    {
        this.bookingDate = bookingDate;
    }

    public Booking(int bookingId, String route, int startTime, String bookingDate)
    {
        setBookingId(bookingId);
        setRoute(route);
        setStartTime(startTime);
        setBookingDate(bookingDate);
    }

    public String toString()
    {
        return "BookingId: " + getBookingId() + "\nRoute: " + getRoute() + "\nStart Time: " + getStartTime() +
                "\nBooking Date: " + getBookingDate();
    }
}

MAIN CLASS

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) throws SQLException {
        //<editor-fold defaultstate="collapsed" desc="Creates new Student and booking">

        Student s1 = new Student();
        Booking b1 = new Booking();
        s1.setStudentId(Integer.parseInt(JOptionPane.showInputDialog("Enter ID for Student: [0001]")));
        s1.setFname(JOptionPane.showInputDialog("Enter first name of Student: "));
        s1.setLname(JOptionPane.showInputDialog("Enter last name of Student: "));
        s1.setAddress(JOptionPane.showInputDialog("Enter address for Student: "));
        s1.setPhoneNo(JOptionPane.showInputDialog("Enter phone number for Student: "));
        s1.setOtherDetails(JOptionPane.showInputDialog("Enter other details for Student: [Glasses?]"));

        b1.setBookingId(0002);
        b1.setStartTime(Integer.parseInt(JOptionPane.showInputDialog("Enter Start time for Booking: [1200]")));
        b1.setBookingDate(JOptionPane.showInputDialog("Enter Date for Booking: [01-JAN-12]"));

       int records = 0;

       List <Booking> allBookings = new ArrayList<Booking>();

       allBookings.add(b1);

       for(Booking b:allBookings) {

           JOptionPane.showMessageDialog(null, b1.getStartTime());//Get Start Time from user

           //<editor-fold defaultstate="collapsed" desc="To select max time of all routes">
           try {
               Class.forName("oracle.jdbc.driver.OracleDriver");
               //load the oracle driver...needs to be in classes folder in jre folder
           } catch (ClassNotFoundException e) {
               System.out.println(
                       " Can't find class oracle.jdbc.driver.OracleDriver");
               System.exit(1);
           }

           Connection conn = null;
           //new connection object
           Statement stmtMax = null;
           //new statemnt object
           ResultSet maxTime = null;
           //new record set object
           try {
               conn = DriverManager.getConnection("jdbc:oracle:thin:@oracle.tralee.ie:1521:orcl",
                       "*", "*");
               stmtMax = conn.createStatement();
               // create the statement for this connection
               //</editor-fold>

               maxTime = stmtMax.executeQuery(
               "SELECT MAX(LENGTH) FROM ROUTE");
               // get the results of select query and store in recordset object
               while (maxTime.next()) {
                   // move to first/next record of recordset
                   JOptionPane.showMessageDialog(null, "Check: Max time of all routes: " + maxTime.getString(1));
                   // output next record using string format
               }
               //<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
               maxTime.close();
               maxTime = null;
               stmtMax.close();
               stmtMax = null;
               conn.close();
               conn = null;

           } catch (SQLException e) {
               System.out.println(" A SQL error: " + e.getMessage());
           } finally {
               if (maxTime != null) {
                   try {
                       maxTime.close();
                   } catch (SQLException ignore) {
                   }
               }

               if (stmtMax != null) {
                   try {
                       stmtMax.close();
                   } catch (SQLException ignore) {
                   }
               }

               if (conn != null) {
                   try {
                       conn.close();
                   } catch (SQLException ignore) {
                   }
               }
           }
          // </editor-fold>
          //<editor-fold defaultstate="collapsed" desc="To select all bookings within a time">
           try {                   Class.forName("oracle.jdbc.driver.OracleDriver");
               //load the oracle driver...needs to be in classes folder in jre folder
           } catch (ClassNotFoundException e) {
               System.out.println(
                       " Can't find class oracle.jdbc.driver.OracleDriver");
               System.exit(1);
           }

错误 -

Connection conn2 = null;
               //new connection object
               Statement stmtTime = null;
               //new statemnt object
               ResultSet withinTime = null;
               //new record set object
               try {
                   conn2 = DriverManager.getConnection("jdbc:oracle:thin:@oracle.tralee.ie:1521:orcl",
                           "*", "*");
                   stmtTime = conn2.createStatement();
                   // create the statement for this connection
                   //</editor-fold>

                   withinTime = stmtTime.executeQuery(
                   "SELECT * FROM BOOKINGS WHERE" + b1.getStartTime() + "<=" + b1.getStartTime() + "-" + maxTime +
                           "AND" + b1.getStartTime() + ">=" + b1.getStartTime() + "+" + maxTime);
                   // get the results of select query and store in recordset object

                     JOptionPane.showMessageDialog(null, " Check: Bookings within a time: \n" + withinTime.getString(1));

                     while (withinTime.next()) {
                       // move to first/next record of recordset
                       JOptionPane.showMessageDialog(null, " Check: Bookings within a time: \n" + withinTime.getString(1));
                       // output next record using string format
                   }
                   //<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
                   withinTime.close();
                   withinTime = null;
                   stmtTime.close();
                   stmtTime = null;
                   conn2.close();
                   conn2 = null;
               } catch (SQLException e) {
                   System.out.println(" A SQL error: " + e.getMessage());
               } finally {
                   if (withinTime != null) {
                       try {
                           withinTime.close();
                       } catch (SQLException ignore) {
                       }
                   }

                   if (stmtTime != null) {
                       try {
                           stmtTime.close();
                       } catch (SQLException ignore) {
                       }
                   }

                   if (conn2 != null) {
                       try {
                           conn2.close();
                       } catch (SQLException ignore) {
                       }
                   }
               }
    //END OF ERROR

//<editor-fold defaultstate="collapsed" desc="To select all free routes">
try {                       Class.forName("oracle.jdbc.driver.OracleDriver");
                   //load the oracle driver...needs to be in classes folder in jre folder
               } catch (ClassNotFoundException e) {
                   System.out.println(
                           " Can't find class oracle.jdbc.driver.OracleDriver");
                   System.exit(1);
               }

               Connection conn3 = null;
               //new connection object
               Statement stmtFreeR = null;
               //new statemnt object
               ResultSet freeRoute = null;
               //new record set object
               try {
                   conn3 = DriverManager.getConnection("jdbc:oracle:thin:@oracle.tralee.ie:1521:orcl",
                           "*", "*");
                   stmtFreeR = conn3.createStatement();
                   // create the statement for this connection

                   freeRoute = stmtFreeR.executeQuery(
                   " SELECT ROUTEID FROM Route MINUS SELECT ROUTEID FROM Booking ");
                   // get the results of select query and store in recordset object

                   while (freeRoute.next()) {
                       // move to first/next record of recordset
                       JOptionPane.showMessageDialog(null, "Check: Select all free RouteId's: " + freeRoute.getString(1));
                       //JOptionPane.showMessageDialog(null, " the answer is " + fRoutes);
                       // output next record using string format
                   }

             //<editor-fold defaultstate="collapsed" desc="To randomize free routes">

   //ERROR -- Does not do anything?

               if( freeRoute != null) {

                List RouteX = new ArrayList();

                while (freeRoute.next()) {
                    RouteX.add(freeRoute.getString(1));

                    Collections.shuffle(RouteX);

                    JOptionPane.showMessageDialog(null, "Free routes list: " + RouteX);

                }
               }
            else {
                List RouteX = new ArrayList();

                while (freeRoute.next()) {
                    RouteX.add(freeRoute.getString(1));

                    Collections.shuffle(RouteX);
                    JOptionPane.showMessageDialog(null,"Free routes list: " + RouteX);
                }
            }

                   //<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
                   freeRoute.close();
                   freeRoute = null;
                   stmtFreeR.close();
                   stmtFreeR = null;
                   conn3.close();
                   conn3 = null;

               } catch (SQLException e) {
                   System.out.println(" A SQL error: " + e.getMessage());

               } finally {
                   if (freeRoute != null) {
                       try {
                           freeRoute.close();
                       } catch (SQLException ignore) {
                       }
                   }

                   if (stmtFreeR != null) {
                       try {
                           stmtFreeR.close();
                       } catch (SQLException ignore) {
                       }
                   }

                   if (conn3 != null) {
                       try {
                           conn3.close();
                       } catch (SQLException ignore) {
                       }
                   }
               }

                //<editor-fold defaultstate="collapsed" desc="To count number of routes">
               try {
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   //load the oracle driver...needs to be in classes folder in jre folder
               } catch (ClassNotFoundException e) {
                   System.out.println(
                           " Can't find class oracle.jdbc.driver.OracleDriver");
                   System.exit(1);
               }

               Connection conn4 = null;
               //new connection object
               Statement stmtCountR = null;
               //new statemnt object
              // ResultSet countRoutes = null;
               //new record set object
               try {
                   conn4 = DriverManager.getConnection("jdbc:oracle:thin:@oracle.tralee.ie:1521:orcl",
                           "*", "*");
                   stmtCountR = conn4.createStatement();
                   // create the statement for this connection
                   //</editor-fold>

                String sql = "SELECT COUNT(*) FROM ROUTE";
                PreparedStatement prest = conn4.prepareStatement(sql);
                ResultSet rs = prest.executeQuery();
                while (rs.next()){
                records = rs.getInt(1);

              }
              //System.out.println("Number of records: " + records);
                       // move to first/next record of recordset
                       JOptionPane.showMessageDialog(null, " Number of total routes: " + records);
                       //JOptionPane.showMessageDialog(null, " the answer is " + fRoutes);
                       // output next record using string format

                   //<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
                  // countRoutes.close();
                   //countRoutes = null;
                   rs.close();
                   rs = null;
                   stmtCountR.close();
                   stmtCountR = null;
                   conn4.close();
                   conn4 = null;

               } catch (SQLException e) {
                   System.out.println(" A SQL error: " + e.getMessage());

               }/* finally {
                   if (countRoutes != null) {
                       try {
                           countRoutes.close();
                       } catch (SQLException ignore) {
                       }
                   }*/

                   if (stmtCountR != null) {
                       try {
                           stmtCountR.close();
                       } catch (SQLException ignore) {
                       }
                   }

                   if (conn4 != null) {
                       try {
                           conn4.close();
                       } catch (SQLException ignore) {
                       }
                   }
               }

    //ERROR - for(r[X]) -- Looking to assign R with an incremented X value. i.e. R1, R2, R3 --

               for(int X = 1; X < records; X++) {

                    for(r[X]) {

                //<editor-fold defaultstate="collapsed" desc="To check if RX is in Collision Table">
               try {
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   //load the oracle driver...needs to be in classes folder in jre folder
               } catch (ClassNotFoundException e) {
                   System.out.println(
                           " Can't find class oracle.jdbc.driver.OracleDriver");
                   System.exit(1);
               }

               Connection conn5 = null;
               //new connection object
               Statement stmtFindRx = null;
               //new statemnt object
               ResultSet checkRx = null;
               //new record set object
               try {
                   conn5 = DriverManager.getConnection("jdbc:oracle:thin:@oracle.tralee.ie:1521:orcl",
                           "*", "*");
                   stmtFindRx = conn5.createStatement();
                   // create the statement for this connection
                       checkRx = stmtFindRx.executeQuery(
                       "*********");
                       // get the results of select query and store in recordset object

                       while (checkRx.next()) {
                       // move to first/next record of recordset
                       JOptionPane.showMessageDialog(null, " the answer is " + checkRx.getString(1));

                       // output next record using string format
                   }
                   //<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
                   checkRx.close();
                   checkRx = null;
                   stmtFindRx.close();
                   stmtFindRx = null;
                   conn5.close();
                   conn5 = null;

               } catch (SQLException e) {
                   System.out.println(" A SQL error: " + e.getMessage());
               } finally {
                   if (checkRx != null) {
                       try {
                           checkRx.close();
                       } catch (SQLException ignore) {
                       }
                   }
                   if (stmtFindRx != null) {
                       try {
                           stmtFindRx.close();
                       } catch (SQLException ignore) {
                       }
                   }

                   if (conn5 != null) {
                       try {
                           conn5.close();
                       } catch (SQLException ignore) {
                       }
                   }
               }
                    }

               }

错误 - 然后检查RX是否=输入的路线,如果他同样加5分钟。

           if(R[X].equals(b1.getRoute())) {

              b1.setStartTime(b1.getStartTime() + 0005);
           } else {

           String strConn = "jdbc:oracle:thin:@oracle.tralee.ie:1521:orcl";
           String strUser = "*";
           String strPassword = "*";

           try {
            Driver drv = new oracle.jdbc.driver.OracleDriver();
            DriverManager.registerDriver(drv);
            Connection conn6 = DriverManager.getConnection(strConn, strUser, strPassword);
            //code to execute commands...

            //Booking Insert
            String query1 = "INSERT INTO Booking(BOOKINGID, BOOKINGTYPE, LNAME, STARTTIME, " +
            "BOOKINGDATE, HISTORY) VALUES (?, ?, ?, ?, ?)";

            PreparedStatement pstmt1 = conn6.prepareStatement(query1);
            pstmt1.setInt(1, b1.getBookingId());
            pstmt1.setDouble(3, b1.getStartTime());
            pstmt1.setString(4, b1.getBookingDate());
            pstmt1.executeUpdate();

            JOptionPane.showMessageDialog(null, "Booking Confirmed");

            conn6.close();
            }

            catch(SQLException e) {
            System.out.println(" A SQL error: " + e.getMessage());
               }
            }
          }
       }

最后一个错误我还没有太烦恼,而且我知道每次创建一个新连接都是不好的,我会在稍后对此进行排序。但就目前而言,我要问的是

1)为什么不发表这个声明:

SELECT * FROM BOOKINGS WHERE" +
 b1.getStartTime() + "<=" + b1.getStartTime() + "-" + maxTime +
 "AND" + b1.getStartTime() + ">=" + b1.getStartTime() + "+" + maxTime);

在开始时间加上所有路线的最长时间后返回预订?以及如何解决此问题?

2)如何调整此值,以便在调用select时返回所有Free未预订路由的值,它会将其插入List中并对列表进行洗牌并返回路由值?

选择运行并返回正确的值,但会出现此错误:

  

ORA-00933:SQL命令未正确结束                    “选择ROUTEID来自Route MINUS SELECT ROUTEID from Booking”);

               while (freeRoute.next()) {
                   JOptionPane.showMessageDialog(null, "Check: Select all free RouteId's: " + freeRoute.getString(1));

               }

           if( freeRoute != null) {
            List RouteX = new ArrayList();

            while (freeRoute.next()) {
                RouteX.add(freeRoute.getString(1));

                Collections.shuffle(RouteX);

                JOptionPane.showMessageDialog(null, "Free routes list: " + RouteX);
            }
           }
        else {
            List RouteX = new ArrayList();

            while (freeRoute.next()) {
                RouteX.add(freeRoute.getString(1));

                Collections.shuffle(RouteX);

                JOptionPane.showMessageDialog(null,"Free routes list: " + RouteX);
            }
        }

而且3)这个for语句,我希望它给R赋值X值,基本上说         对于每个R [X值]然后是for语句的主体?

for(int X = 1; X < records; X++) {

                for(r[X]) {

我知道我在这里问了很多,但是如果有人能够阐明我需要改变什么才能让这些东西解雇,那就非常感激了。

编辑:

预订表

    CREATE BOOKING
      (
        BOOKINGID NUMBER(4,0),
        STARTTIME NUMBER(4,0),
        BOOKINGDATE DATE,
        EXAMINERID NUMBER(4,0),
        STUDENTID  NUMBER(4,0),
        ROUTEID    NUMBER(4,0),
        CONSTRAINT BOOKING_PK PRIMARY KEY (BOOKINGID)
CONSTRAINT EXAMINER_FK FOREIGN KEY (EXAMINERID) REFERENCES EXAMINER,
CONSTRAINT STUDENT_FK FOREIGN KEY (STUDENTID) REFERENCES STUDENT,
CONSTRAINT ROUTE_FK FOREIGN KEY (ROUTEID) REFERENCES ROUTE);

1 个答案:

答案 0 :(得分:0)

刚开始我认为你应该看一下mysql的时间函数。 http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_addtime更具体地说是addtime函数。

我不确定您要验证的列的确切类型,但查询似乎没有验证该列

SELECT * FROM BOOKINGS WHERE" + b1.getStartTime() + "<=" + b1.getStartTime() + "-" + maxTime + "AND" + b1.getStartTime() + ">=" + b1.getStartTime() + "+" + maxTime);

开始时间的预订表列是什么。您在运行当前的查询将如下所示:

select * from bookings where12<=12-5and12>=12+5

我强烈建议您首先使用字符串分配查询字符串并使用控制台输出语句,这样您就可以轻松地调试语句而无需其他应用程序。我还建议您阅读有关参数化查询的内容,因为您将用户输入权限传递给查询,这是SQL注入的一个大门。看到这个链接:

http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

如果您发布预订表架构,我相信我们可以根据您的要求帮助您构建正确的查询。

修改

这可能不是您需要的查询,但它会为您提供一个良好的起点。我强烈建议您首先在sql plus中使用您正在使用的任何工具来调试查询。

PreparedStatement prest;
Connection conn2 = DriverManager.getConnection("jdbc:");//set you jdbc url
String sql = "select * from bookings where bookingdate = ? and starttime between ? and ?";
prest = con.prepareStatement(sql);
prest.setDate(1,b1.getBookingDate());
prest.setInt(2,b1.getStartTime()-5);
prest.setInt(3,b1.getStartTime()+5);
ResultSet rs1 = prest.executeQuery();
while(rs1.hasNexT())
    //extract data here