Solved

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

Posted on 2002-04-13
4
258 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
ID: 6939380
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
ID: 6939386
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
ID: 7940662
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
ID: 7990832
Finalized as proposed

modulo

Community Support Moderator
Experts Exchange
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
V.simple question about Android packages and libraries 1 29
varialbe initialization 11 37
Is there a simpler dropbox system? 10 34
Html Table Looping (part 2) 5 27
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

840 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