Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Trying to insert checkbox array into single DB cell.

Posted on 2006-11-12
19
Medium Priority
?
238 Views
Last Modified: 2010-03-31
I have a servlet that retrieves all checked boxes of a certain name into an array (currently i have two set up below).  I want to convert that array into a String using comma delimitation and have it inserted into my DB.  I seem to be having a problem converting this string- the problem is my lack of know how.

I will post the important parts of my servlet so everyone can see how it looks.  This servlet might have some garbage code in there- i've been messing with this for hours trying to get it to work.

Thank you in advance to anyone who can get this working properly.  It's been a massive headache.


[code]
package savedata;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;

public class MandatoryServlet extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading All Request Parameters";
    Enumeration paramNames = request.getParameterNames();
            while(paramNames.hasMoreElements()) {
              String paramName = (String)paramNames.nextElement();
              //out.println("<TR><TD>" + paramName + "\n<TD>");
              for(int count = 0; count<20; count++){
                    String[] exterior = request.getParameterValues("frmExterior"+count);

                                    if(exterior == null) {
                                    } else {
                                          for(int i=0; i<exterior.length; i++) {
                                                if(exterior.length != 0) {
                                                out.print("frm"+count +exterior[i] +",");
                                                getServletContext().setAttribute("foo", exterior);
                                                out.print(getServletContext().getAttribute("foo").setArray());
                                                }
                                          }
                                      }
                        
                    String[] fincancing = request.getParameterValues("frmFinancing"+count);
                                    if(fincancing == null) {
                                    } else {
                                          for(int i=0; i<fincancing.length; i++) {
                                                if(fincancing.length != 0) {
                                                out.print("frm"+count +fincancing[i] +",");
                                                }
                                          }
                                      }
                        }
                        break;
            
      
    }
      out.println("<a href=uadmin/b/requestdatafromservlettest.jsp>asdasd</a>");
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
 
 
  public void insert() {
    Connection con = null;
      PreparedStatement prep = null;
      String sql = null;
      ResultSet result;
      

    try {
      Class.forName("org.gjt.mm.mysql.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jobprop?user=xxx&password=");

      if(!con.isClosed())
        System.out.println("Successfully connected to " +
          "MySQL server using TCP/IP...");
             
                          try
            {
            sql = "INSERT INTO form_main(username)VALUES(?)";            
            prep = con.prepareStatement(sql);
prep.setString(1, getServletContext().getAttribute("foo").setArray());
            prep.executeUpdate();
           }
           catch(Exception m)
           {
            System.out.print(m.getMessage());
           }

    } catch(Exception e) {
      System.err.println("Exception: " + e.getMessage());
    } finally {
      try {
        if(con != null)
          con.close();
      } catch(SQLException e) {}
    }
  }

 
}
[/code]
0
Comment
Question by:domoaarongato
  • 11
  • 8
19 Comments
 
LVL 16

Expert Comment

by:suprapto45
ID: 17927581
I think that you can use String to accomplish that.

Are these the codes that you are talking about?

                 String[] fincancing = request.getParameterValues("frmFinancing"+count);
                              if(fincancing == null) {
                              } else {
                                   for(int i=0; i<fincancing.length; i++) {
                                        if(fincancing.length != 0) {
                                        out.print("frm"+count +fincancing[i] +",");
                                        }
                                   }

If so, can you tell me what the problem with the current codes?

David
                   
0
 

Author Comment

by:domoaarongato
ID: 17927685
yes. that is the code im talking about.  I will also need to pass exteriors to the same row- but i figure that i can do that after i learn how to do this.

[code]
I cannot javac the above class because it throws the below error.
MandatoryServlet.java:31: cannot find symbol
symbol  : method setArray()
location: class java.lang.Object
                                        out.print(getServletContext().getAttribu
te("foo").setArray());
                                                                   ^
freeholdMandatoryServlet.java:79: cannot find symbol
symbol  : method setArray()
location: class java.lang.Object
prep.setString(1, getServletContext().getAttribute("foo").setArray());
                                   ^

[/code]


I don't even know if set/getAttribute is the correct way of going about this.
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17927871
I am quite confused with your codes as well.

Why do you need to use getServletContext().getAttribute("foo").setArray()?

First, you have parsed all the information in your doGet method. If it works correctly, you can just pass the parameters to the insert() method. For example,

                 String fincancingResult = "";
                 String[] fincancing = request.getParameterValues("frmFinancing"+count);
                              if(fincancing == null) {
                              } else {
                                   for(int i=0; i<fincancing.length; i++) {
                                        if(fincancing.length != 0) {
                                        //out.print("frm"+count +fincancing[i] +",");
                                        fincancingResult  = "frm"+count +fincancing[i] +",";
                                        }
                                   }

                             insert (fincancingResult);

Then in your insert method,

public void insert(String fincancingResult) {

}

Now, the result is available to your insert method.

David
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:domoaarongato
ID: 17927912
I was told that to pass a value to another method i may need to set and attribute.  i've since learned this is incorrect.

Can i pass more than one parameter to the insert() method?

I will try your code out very shortly.   I hope it works:)
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17927921
Yes, why not?

For example,

String a = "David";
String b = "domoaarongato ";

insert (a, b);

then in your insert method,

public void insert(String a, String b) {
  // now you can access String a and String b.
}
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17927924
>>"I was told that to pass a value to another method i may need to set and attribute."
You may need this if you want to send the values FROM your Servlet to your JSP or vice versa. However, your problem is on the Servlet itself so they all are in one *scope* so you should not sue set / get attribute
0
 

Author Comment

by:domoaarongato
ID: 17927959
I seem to be getting an error when i javac
MandatoryServlet.java:81: cannot find symbol
symbol  : variable fincaningResult
location: class savedata.MandatoryServlet
prep.setString(1, fincaningResult);
                  ^


Thanks for the assistance so far. I appreciate it.
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17927975
Is that fincaningResult or fincancingResult?

Is that typo?
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17927979
Will be back later on....
0
 

Author Comment

by:domoaarongato
ID: 17927991
ahhm, typo...

one last thing. i trigger this insert via jsp. i normally use

<jsp:useBean id="save" class="savedata.MandatoryServlet" scope="session"/>
<% save.insert();%>

but this wont work anymore.

ive also tried <% save.insert(fincancingResult);%> and <% save.insert(String fincancingResult);%> with no luck.
0
 
LVL 16

Accepted Solution

by:
suprapto45 earned 2000 total points
ID: 17928138
Hi domoaarongato,

Now, your logic to parse this is on your doGet method and the doGet method will subsequently call the insert method. You do not need to call it directly from your JSP using the <jsp:useBean>. What you need to do now is to submit the form that goes to MandatoryServlet.

<form action="/MandatoryServlet" method="GET">
    <%-- All the HTML components here --%>

    <input type="submit" value="Submit">
</form>
0
 

Author Comment

by:domoaarongato
ID: 17928189
Hmm. nothing is entering into the DB.

here's what i have
          sql = "INSERT INTO form_main(username)VALUES(?)";          
          prep = con.prepareStatement(sql);
          prep.setString(1, fincancingResult);
          prep.executeUpdate();


If i put something static into the setString the static value inserts..
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17928195
Then,

Do a little debugging....

          sql = "INSERT INTO form_main(username)VALUES(?)";          
          prep = con.prepareStatement(sql);
 
          System.out.println("fincancingResult = " + fincancingResult);
          prep.setString(1, fincancingResult);
          prep.executeUpdate();

and see what does it print in the console?
0
 

Author Comment

by:domoaarongato
ID: 17928197
actually, wait. a static value isnt inserting anymore.. hmm..
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17928201
>>"actually, wait. a static value isnt inserting anymore.. hmm.."
It may be because the insert method is not executed at all. Okay, for ease, can you post your current Servlet and JSP so that I can inspect?
0
 

Author Comment

by:domoaarongato
ID: 17928215
ok, i found the screw up. my mistake.  IT works!  but something is happening that i didnt account for.  It's inserting each value into the db one row at a time, so if i have three checkbox results, it puts them in three rows.

i'm giving you the 500 points for fixing my problem!  let me know if you don't get them.  ive never doen this before.

P.S let me know if you have a solution for the seperate rows prolblem.
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17928220
>>"ok, i found the screw up. my mistake.  IT works!"
:)

>>"It's inserting each value into the db one row at a time, so if i have three checkbox results, it puts them in three rows."
Then, I'll be asking you.

What is the purpose of "for(int count = 0; count<20; count++){"?
0
 

Author Comment

by:domoaarongato
ID: 17928254
That is to set how many times it can loop. i set it to 20 incase there are ever 20 options selected.  Ideally that should be dynamic- but i didnt know how to do it so i made it a static 20. if i need to make it mroe later i can change the 20 to something higher.
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17928270
I think that the solution to your problem would be bringing out the insert method from this for loop.

I can't help much now as I have something to do. You may be interested to open up another question so other experts can help you or I can pop in later on

David
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
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 …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

971 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