Solved

(megloff) MoreInformation for Inserting Multiple records into a Table (Servlets and Database)

Posted on 2002-04-13
4
255 Views
Last Modified: 2013-11-24
I had this problem for the last three weeks and this code I need it for the school project (i.e. the school project intrduced me to servlets for the first time). So the thing which drove me to insert multiple fields from the html is because I cannot get the shopping chart started. So I opted for inserting  multiple records of the same data.The code I have developed with the help from you guys only insert the first record and leaves the others without inserting them to the database.

My HTML page looks like this


FORM ACTION="http://192.168.100.237:8080/200003668/servlet/OrderPlacementServlet" METHOD="post">


TABLE CELLPADDING = 0 CELLSPACING = 0 ALIGN = "LEFT" BORDER = 2 BACKGROUND="http://192.168.100.237:8080/200003668/images/glowBg.gif">

tr>

td>b> CUSTOMER ID:  b>/td>

td>INPUT TYPE="TEXT" NAME="CustomerId"   size = 15>/td>

/tr>

tr>

td>b> DATE:  b>/td>


td>INPUT TYPE="TEXT" NAME="DateOrdered"   size = 15>/td>

/tr>


/table>








TABLE CELLPADDING = 0 CELLSPACING = 0 ALIGN = "LEFT" BORDER = 2 BACKGROUND="http://192.168.100.237:8080/200003668/images/glowBg.gif">



tr>

td>center>b>QUANTITY/b>/center>/td>

td>center>b>ANIMAL CODE/b>/center>/td>

td>center>b>UNIT PRICE/b>/center>/td>


/tr>

tr>

td>INPUT TYPE="TEXT" NAME="Quantity"   size = 15>/td>
td>INPUT TYPE="TEXT" NAME="AnimalCode"   size = 15>/td>
td>INPUT TYPE="TEXT" NAME="UnitPrice" size = 15>/td>

/tr>

tr>

td>INPUT TYPE="TEXT" NAME="Quantity"   size = 15>/td>
td>INPUT TYPE="TEXT" NAME="ANIMALCode"   size = 15>/td>
td>INPUT TYPE="TEXT" NAME="UnitPrice" size = 15>/td>

/tr>
/TABLE>


And My OrderPlacementServlet Looks like this


import java.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;


public class OrderPlacementServlet extends HttpServlet

{

 private Connection conn = null;
 private Statement stat = null;
 String url = "jdbc:odbc:animal";

 String img = "http://192.168.100.237:8080/200003668/images/BannerPic.jpe";
 String strUrl ="http://192.168.100.237:8080/200003668/servlets/Project/OrderNow2.htm";

 public void doPost(HttpServletRequest req, HttpServletResponse res)

 throws ServletException, IOException{

PrintWriter out = res.getWriter();
res.setContentType("text/html");

String CustomerId   = req.getParameter("CustomerId");
String DateOrdered    = req.getParameter("DateOrdered");
String Quantity       = req.getParameter("Quantity");
String AnimalCode    = req.getParameter("AnimalCode");
String UnitPrice      = req.getParameter("UnitPrice");
String TotalCost      = req.getParameter("TotalCost");

out.println("<html>");
out.println("<head>");
out.println("<title>Thanks</title>");
out.println("</head>");

out.println("<center><IMG SRC = "+ img + "  width = 80%></center>");

out.println("<body background = http://192.168.100.237:8080/200003668/images/RabbitsBg.gif>");

out.println("<h4>Thank you,  " + CustomerId +" <br></h4>");

out.println("<center><h4>THE ITEMS WILL BE DELIVERED AT YOUR DOOR STEP  <br></h4></center>");
out.println("<a href = "+ strUrl +"><center><h3>Go To Order Page</h3></center></a>");
out.println("</body>");

out.println("</html>");

if (TotalCost.equals(" ")&& UnitPrice.equals(" ")) {

out.println("Cannot submit an empty entry");

out.close();
return;

}

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn = DriverManager.getConnection(url,"","");
}

catch (Exception e) {

out.println("Error: cannot connect to the db");
out.print(e);

}

String SQL = "INSERT INTO ORDERS(CustomerId,DateOrdered,Quantity,AnimalCode,UnitPrice,TotalCost)VALUES(?,?,?,?,?,?)";

try{

 PreparedStatement  stmt = conn.prepareStatement(SQL) ;

        stmt.setString(1,  CustomerId  );
        stmt.setString(2,  DateOrdered);
        stmt.setString(3,  Quantity);
        stmt.setString(4,  AnimalCode);
        stmt.setString(5,  UnitPrice);
        stmt.setString(6,  TotalCost);

        stmt.executeUpdate();

}

catch (SQLException e) {

out.println("Cannot connect");

out.print(e);

out.println("<body bgcolor = brown>");

out.println("<h4>Thank You  <br></h4>");

out.println("</body>");

out.println("</html>");





try {

conn.close();

}

catch (SQLException s) {

out.println("Error unable to connect");

}

}

}
}



I tried using while (result.next()) but it couldn't work and  megloff where do I put your line statements on the above code (i.e. getParameters("")). I would like to thank you guys for this project success and now I am only left with the above objective as a replacement of the shopping chart servlet coz I don't really get it started unless you opt to assist me in the shopping cart using servlets

for more info please email me at (wbmorapedi@yahoo.com)


Willing
0
Comment
Question by:wbmorapedi
  • 2
4 Comments
 

Accepted Solution

by:
megloff earned 70 total points
Comment Utility
If this example is what you want so it is easy...

- You must have a unique delimiter in your input fields as like as your comma.

- Input data from html pages are Strings

1. so first fill in your inputs into strings
2. use a java.util.StringTokenizer (or another parser technique) to split it into the records
3. save the records to the database

String names = request.getParameter("NAME");
String ages  = request.getParameter("AGE");

StringTokenizer toki1 = new StringTokenizer(names,",");
StringTokenizer toki2 = new StringTokenizer(ages,",");
// amount of tokens has to be the same
if ( toki.countTokens() != toki2.countTokens() )

   throw Exception("Wrong amount of inputs...");











 
0
 

Expert Comment

by:megloff
Comment Utility
If this example is what you want so it is easy...
Here is a shorted version. If you want have more details
so please send me a note....

- You must have a unique delimiter in your input fields as like as your comma.

- Input data from html pages are Strings

1. so first fill in your inputs into strings
2. use a java.util.StringTokenizer (or another parser technique) to split it into the records
3. save the records to the database

String names = request.getParameter("NAME");
String ages  = request.getParameter("AGE");

StringTokenizer toki1 = new StringTokenizer(names,",");
StringTokenizer toki2 = new StringTokenizer(ages,",");
// amount of tokens has to be the same
if ( toki.countTokens() != toki2.countTokens() )
  // do an error notification, send something back...
  throw Exception("Wrong amount of inputs...");

while( toki1.hasMoreElements() )
{
     String name = toki1.nextElement();
     String age  = toki2.nextElment();

     // call function to store it into a database
    store recordtoDatabase(name,age);
}



0
 
LVL 9

Expert Comment

by:Venci75
Comment Utility
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
Answered by: megloff
Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Venci75
EE Cleanup Volunteer
0
 

Expert Comment

by:modulo
Comment Utility
Finalized as proposed

modulo

Community Support Moderator
Experts Exchange
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
return in catch statement 1 39
wordlen challenge 3 46
pairs challenge 5 44
eclipse java  build path 6 17
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now