Solved

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

Posted on 2002-04-13
4
256 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
custom annotations 9 31
jar file executable 12 40
Basic Java Case or If-Else statement... 3 43
servlet doXXX methods 3 36
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

910 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

23 Experts available now in Live!

Get 1:1 Help Now