Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2004

Tip: Looking for answers? Try searching our database.

Update functionality error

Thread view: 
Mohammed Mazid - 29 Mar 2004 20:28 GMT
Can anyone please help me here?  Basically I have modified the source
code and understood it but when I update a record in the db using a
JSP, it gives me an error "The flight you selected does exist."

Althought there is not selection going on, instead it is entered, I
need it to match the flight in the db using the flightNo.  I want all
the attributes to be changed apart from the flightNo itself as it is
it's associated details I need changing (i.e. flightdate, destination,
arrTime and depTime).

Below are the code snippets but did not include everything as all
details were not neded.  Therefore I had put part of it.  But
somewhere I am going wrong of "updating" a db record.

public class Flight
{
 String flightNo;
 Date flightDate;
 String destination;
 Time arrTime;
 Time depTime;

 Flight(String flightNo, Date flightDate, String destination, Time
arrTime, Time depTime)
 {
  this.flightNo = flightNo;
  this.flightDate = flightDate;
  this.destination = destination;
  this.arrTime = arrTime;
  this.depTime = depTime;
 }

 public String getFlight()  
 {
   return flightNo;
 }
 public Date getFlightDate()
 {
   return flightDate;
 }
 public String getDestination()
 {
   return destination;
 }
 public Time getArrTime()
 {
   return arrTime;
 }
 public Time getDepTime()
 {
   return depTime;
 }
 public String toString()
 {
   return flightNo;
 }
}

public class FlightService
{
 private FlightDAO flightDataAccess;

 public FlightService()
 { flightDataAccess = new FlightDAO(); }

 public Flight getFlight(String flightNo)
 {
   Flight flight = null;

   try
   {
     flight = flightDataAccess.retrieve(flightNo);
   }
   catch (ObjectNotFoundException onfe) { flight = null; }

   return flight;
 }

 public Flight updateFlight(String flightNo, Date flightDate, String
destination, Time depTime, Time arrTime)
 {
  Flight flight = new Flight(flightNo, flightDate, destination,
  depTime, arrTime);

 // Perform the DB transaction
 flightDataAccess.update(flight);

 return flight;
 }
}

class FlightDAO
{
 FlightDAO() {}

 Flight retrieve(String flightNo)
        throws ObjectNotFoundException {

   // Assume everything is declared

   try
{
     // Get a database connection
     connection = connectionPool.getConnectionNoWait();

     // Create SQL SELECT statement
     stmt = connection.prepareStatement(RETRIEVE_STMT);

     // Initialize statement and execute the query
     stmt.setString(1, flightNo);
     results = stmt.executeQuery();

     // Iterator over the query results
     while ( results.next() )
  {
       // We expect only one row to be returned
       num_of_rows++;
       if ( num_of_rows > 1 )
 {
         throw new SQLException("Too many rows were returned.");
       }

       // Create and fill-in the Flight object
       flight = new Flight(results.getString("FlightNo"),
                           results.getDate("FlightDate"),
                           results.getString("Destination"),
                           results.getTime("ArrivalTime"),
      results.getTime("DepartureTime"));
     }

     if ( flight != null ) { return flight; }
     else { throw new ObjectNotFoundException();  }

   // Handle any SQL errors
   }
catch (SQLException se)
{
     throw new RuntimeException("A database error occured. " +
se.getMessage());

//Some more catch statements and finally blocks exist.
 }

 private static final String RETRIEVE_STMT
   = "SELECT FlightNo, FlightDate, Destination, ArrivalTime,
DepartureTime FROM Flight WHERE FlightNo = ?";

 void update(Flight flight) {

   // Assume all declared

   PreparedStatement update_stmt = null;

   try {
     // Get a database connection
     connection = connectionPool.getConnectionNoWait();

     // Create SQL INSERT statement
     update_stmt = connection.prepareStatement(UPDATE_STMT);

     // Add data fields
     update_stmt.setDate(1, flight.flightDate);
     update_stmt.setString(2, flight.destination);
     update_stmt.setTime(3, flight.arrTime);
  update_stmt.setTime(4, flight.depTime);

     // Execute SQL INSERT statement
     update_stmt.executeUpdate();

   // Handle any SQL errors
   }
catch (SQLException se)
{
     throw new RuntimeException("A database error occured. " +
se.getMessage());

//Assume catch and finally block exist
     }
   }
 }

private static final String UPDATE_STMT
= "UPDATE Flight SET FlightDate = ?, Destination = ?, ArrivalTime =
?, DepartureTime = ? WHERE FlightNo = ?";
}

//Assume all imports exist

public final class FlightServlet extends HttpServlet
{
 public void doPost(HttpServletRequest request,                  
HttpServletResponse response)
        throws IOException, ServletException {

   processRequest(request, response);
 }

 public void processRequest(HttpServletRequest request,
                            HttpServletResponse response)
        throws IOException, ServletException {
   // Declare the dispatcher for the View
   RequestDispatcher view = null;

   // Declare service and database variables
   FlightService flightSvc;
   Flight flight = null;

   // Create the status object and store i tin the request for use
   // by the 'Error Page' View (if necessary)
   Status status = new Status();
   request.setAttribute("status", status);

   // Extract HTML form parameters
   String flightNo = request.getParameter("flightNo");
   
String dateString = request.getParameter("flightDate");
Date flightDate = Date.valueOf(dateString);
 
String destination = request.getParameter("destination");

String timeString = request.getParameter("depTime");
Time depTime = Time.valueOf(timeString + ":00");

String timeStr = request.getParameter("arrTime");
Time arrTime = Time.valueOf(timeStr + ":00");

   // Assume there are if-else statements

   // Now delegate the real work to the FlightService object
   try
{
     // Create the "flight service" object
     flightSvc = new FlightService();

     // Check if this flight object already exists
     flight = flightSvc.getFlight(flightNo);
     if ( flight != null )
  {
       status.addException(
           new Exception("The flight you selected already exists;"));
     }

     // If any of the above verification failed, then return the
     // 'Update Flight Form' View and return without proceeding with
the
     // rest of the business logic
     if ( ! status.isSuccessful() ) {
       view = request.getRequestDispatcher("updateform.jsp");
       view.forward(request, response);
       return;
     }

     // Add the flight to the data-file
     flight = flightSvc.updateFlight(flightNo, flightDate,
destination,
  depTime, arrTime);
     request.setAttribute("flight", flight);

     // The flight update process was successful,
     // forward to the 'Flight Updated' View
     view = request.getRequestDispatcher("thank_you.jsp");
     view.forward(request, response);

   // Handle any business logic errors
   } catch (Exception e) {
     status.addException(e);
     view = request.getRequestDispatcher("updateform.jsp");
     view.forward(request, response);
   }
 }
}

Can anyone please suggest where to change and what would be the
correct code fragment?  I'd be really appreciated.  Thanks for your
contribution.
Andrew Thompson - 29 Mar 2004 20:49 GMT
> Can anyone please help me here?  Basically I
> have modified the source code

So you got it from ..where?  

>..and understood it

That's debatable.

>..but when I update a record in the db using a
> JSP, it gives me an error "The flight you selected does exist."

I suggest if the code you 'got' worked,
do not touch it; if you are learning
Java, start with much simpler things;
and for anything else - hire someone.

Signature

Andrew Thompson
http://www.PhySci.org/ Open-source software suite
http://www.PhySci.org/codes/ Web & IT Help
http://www.1point1C.org/ Science & Technology

Peter Kirk - 30 Mar 2004 16:19 GMT
<snip>

>       // Create SQL INSERT statement
>       update_stmt = connection.prepareStatement(UPDATE_STMT);
[quoted text clipped - 4 lines]
>       update_stmt.setTime(3, flight.arrTime);
>    update_stmt.setTime(4, flight.depTime);

Don't you need to set the "FlightNo" here as well?

<snip>

> private static final String UPDATE_STMT
>  = "UPDATE Flight SET FlightDate = ?, Destination = ?, ArrivalTime =
> ?, DepartureTime = ? WHERE FlightNo = ?";
> }
Mohammed Mazid - 30 Mar 2004 22:16 GMT
No, I am updating flight details according to "FlightNo".  Let's say
that for example, the departure time or the date of flight changes of
the same flight, I need to for example, a flight BA123 is on
29-03-2004, but is on 31-03-2004.  I think the only problem here,
apart from all the set methods which are valid, is that the flightNo
cannot be identified from the database.  I am getting to many "COUNT
field inccorect" errors when I always submit a record.

Basically I need someone to tell me how I could sort of "get" the
flightNo so that when I enter a e.g. flightNo BA123, which exists in
the db, it should be able to match that flight in the db entry.

So can anyone please give me some help as I have tried my utter best?

I will be appreciated for your contribution.

Thanks

> <snip>
>
[quoted text clipped - 15 lines]
> > ?, DepartureTime = ? WHERE FlightNo = ?";
> > }
Peter Kirk - 31 Mar 2004 09:47 GMT
> No, I am updating flight details according to "FlightNo".  Let's say
> that for example, the departure time or the date of flight changes of
[quoted text clipped - 7 lines]
> flightNo so that when I enter a e.g. flightNo BA123, which exists in
> the db, it should be able to match that flight in the db entry.

What exactly is "flightNo", is it a String like "BA123" ?

My previous comment was concerning the fact that there was at least a
mismatch between your update statement and the prepared statement.

Your update statement is:
private static final String UPDATE_STMT
= "UPDATE Flight SET FlightDate = ?, Destination = ?, ArrivalTime =
?, DepartureTime = ? WHERE FlightNo = ?";

Yet when you prepare your statement you do:
     update_stmt = connection.prepareStatement(UPDATE_STMT);
     // Add data fields
     update_stmt.setDate(1, flight.flightDate);
     update_stmt.setString(2, flight.destination);
     update_stmt.setTime(3, flight.arrTime);
  update_stmt.setTime(4, flight.depTime);

So you miss something like
  update_stmt.setString(5, filght.getFlight());

Peter


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.