PreparedStatement.executeBatch() Not Working

Hello,
I'm having a problem with the executeBatch() command. It seems that whenever I used it, my program just hangs up. What this program do is that it first read a text file and place it in an Array. Then it would also read the Database and place the contenent of the table in an array as well. Each Array has at least 100,000 records. If the record from the textfile and the database matches, it would update the table using a preparedStatement.addBatch() command. After the said loop, it is then that the int[] cnt = preparedStatement.executeBatch() command is called. and that is when the Hanging part begins. Can you help me.
Thanks.

Hello,
Yes, i'm using a JDBC-ODBC bridge. The dirver is (sun.jdbc.odbc.jdbcodbcdriver). I tried examining the program patiently waited, and eventually it did not hang anymore. At first instance, I did gave the program some time and look if it really hangs, but after 15-30 mins, it work but the the second executeBatch() didn't work. There were no errors or exception that were caught.
Thanks.
Hi,
What driver are you using? And are you using the JDBC
- ODBC bridge? Please post the exact error message you
are getting when you try to do executeBatch().
Nish

Similar Messages

  • PreparedStatement & MySql not working ! Why ?!!?

    Hello everyone. One question for you : I try to have a SELECT on a table to get a column value. I've used for that a preparedstatement but id didn't worked, I mean it returned nothing. Then I've used a simple statement which worked correctly. My question is why prepared doesn't work while simple statement do ?! Other querys work fine, but this one doesn't. And I simply don't get it... I need this preparedstatement way because I use this query very often.
    I use MySQL Connector/J latest version, Java 1.4. Here's the code for this situation:
    This doesn't work:
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE MSISDN = ? AND SUBSCRIBER_TYPE = 0 AND RIGHTS <> 1 LIMIT 1";
    PreparedStatement pstm = null;
    ResultSet rs = null;
    pstm = serviceConnection.prepareStatement(sql);
    pstm.setString(1, MSISDN);
    rs = pstm.executeQuery();
    //gets the iduser from the query
    if (rs.next())
    iduser = rs.getInt("IDUSER");
    else
    iduser = 0;
    This works:
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE MSISDN = "+MSISDN+" AND SUBSCRIBER_TYPE = 0 AND RIGHTS <> 1 LIMIT 1";
    Statement stm = null;
    ResultSet rs = null;
    stm = serviceConnection.createStatement();
    rs = stm.executeQuery(sql);
    //gets the iduser from the query
    if (rs.next())
    iduser = rs.getInt("IDUSER");
    else
    iduser = 0;
    Thank's in advance.

    MSISDN is a String or is a number?
    The non PreparedStatement code works if the sql has
    quotes arrounf this field?
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE
    MSISDN =' "+MSISDN+"' AND SUBSCRIBER_TYPE = 0 AND
    RIGHTS <> 1 LIMIT 1";
    This is something simmilar to the use of
    PreparedStatement.setString();
    The setters of prepared statements are not a simple
    substitution in the sql string. Your database probably
    are thinking that there aren't any row with "not a
    number" in the MSISDN column.The MSISDN is a String representation of a number. And it works with/without the ' around for statements. What's strange is that if I change the prepared statement to be like this:
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE MSISDN = "+MSISDN+" AND SUBSCRIBER_TYPE = 0 AND RIGHTS <> 1 LIMIT 1",
    and I don't use the setString() method it still doesn't work :((

  • Like clause in PreparedStatement not working

    Hi
    I need to create a PreparedStatement that selects using a like where clause. I do the following:
    String param0 = "ABC%";
    PreparedStatement pstmt = conn.prepareStatement("select ISSUEID from DMFI_ISSUE where ISIN like ?");
    setObject(pstmt,1,param0,java.sql.Types.VARCHAR);
    This doesn't work. If param0 is set to the exact value in the database (e.g. "ABCDEF") it selects one, but the like is not working. Is this a jdbc bug? I need to use a PreparedStatement.
    Can anyone help?
    Thanks

    Please ignore, mea culpa, just a vagary of the dos shell. I passed in "abc%" from the dos prompt.

  • PreparedStatement not working with Oracle

    Hi All,
    I am using preparedStatement in my JDBC code to fetch/insert values from oracle9i database.
    I am checking condition like if a given record does not exist then insert it else update it.
    First time it works when there is no row in database, however for subsequent run it's not able to return me the result though that row exist in database and this resulting in DuplicateKeyException becuase it try to create the row in db again.
    The code is working fine for MySQL DB2 and SQLServer but doesn't work in case oracle 9i
    Here is mycode
    //problem is here 1st time it works next time it is not retunring true though record is there in DB.
    if(isItemExist("1","CORP"))
    updateItem("1","CORP","DESC1");
    else
    insertItem("1","CORP","DESC1");
    public boolean isItemExist(String itemid, String storeid)
    String FIND_SQL = "SELECT item_desc from item where item_id = ? and store_id = ? ";          
    c = utils.getConnection();
    ps = c.prepareStatement();
    int i = 1;
    ps.setString(i++, storeid);
    ps.setString(i++, itemid);
    rs = ps.executeQuery();
    if(rs.next()){
         return true;
    utils.close(c, ps, rs);
    else{
         return false;
    utils.close(c, ps, rs);
    public void createItem(String itemid, String storeid, String item_desc)
    String INSERT_SQL = "INSERT INTO item(item_id,store_id,item_desc)values(?, ?, ?)";
    c = utils.getConnection();
    ps = c.prepareStatement();
    int i = 1;
    ps.setString(i++, itemid);
    ps.setString(i++, storeid);
    ps.setString(i++, item_desc);
    ps.executeUpdate();
    utils.close(c, ps, null);
    public void updateItem(String itemid, String storeid, String item_desc)
    String INSERT_SQL = "UPDATE item SET item_desc = ?, store_id=? WHERE item_id = ?";
    c = utils.getConnection();
    ps = c.prepareStatement();
    int i = 1;
    ps.setString(i++, item_desc);
    ps.setString(i++, storeid);
    ps.setString(i++, itemid);
    ps.executeUpdate();
    utils.close(c, ps, null);
    Kindly suggest what's wrong with code. because same code works with other databse like SQL Server, MySQL but it is not working with oracle9i.

    if(isItemExist("1","CORP"))
    updateItem("1","CORP","DESC1");
    else
    insertItem("1","CORP","DESC1");
    String FIND_SQL = "SELECT item_desc from item where item_id = ? and store_id = ? ";
    ps.setString(i++, storeid);
    ps.setString(i++, itemid);
    String INSERT_SQL = "INSERT INTO item(item_id,store_id,item_desc)values(?, ?, ?)";
    ps.setString(i++, itemid);
    ps.setString(i++, storeid);
    ps.setString(i++, item_desc);
    String INSERT_SQL = "UPDATE item SET item_desc = ?, store_id=? WHERE item_id = ?";
    ps.setString(i++, item_desc);
    ps.setString(i++, storeid);
    ps.setString(i++, itemid);My first guess, looking at the above snippets, would be that the item_id field is a number and not a string and so you should be calling ps.setInt instead of ps.setString when setting that parameter.
    This is only a guess, however, since you have not posted what the actual error is, which will probably give a hint to what the actual error is.

  • PreparedStatements not working

    I have just set up a web application on a server only for some reason, prepared statements do not seem to be working. It is running jdk1.3 and tomcat and mysql. It all works fine on my local machine but when placed on the server the preparedstatements are not recognised. Does anyone have any ideas how to remedy this?
    Thanks

    Hi,
    try loads of debugging using system.out.prinln statements which will show up in the log and also in the tomcat batch window. You'll probably find you are not passing the correct or null variables into the statement, maybe.
    best,
    kev

  • IMAGEIO IS WORKING BUT BYTEARRAY IS NOT WORKING:

    Hi all
    I am getting images from gmail contacts and trying to store it in DB
    using my http code:InputStream is=urlconnection.getInputStream();
    i could able to store the inputstream in file using:
    BufferedImage filebuffer=ImageIO.read(is);
    FileOutputStream fos=new FileOutputStream("picturerecent.jpg");
    ImageIO.write(filebuffer, "jpg", fos);
    but i was trying to store it in DB using the following code but it is not working.i am having a question that
    how it writing to a file without any problem.why not to database:
    try {
           String url = "jdbc:mysql://localhost:3306/";
             String db = "test";
             String driver = "com.mysql.jdbc.Driver";
                    Class.forName(driver);
                    con = DriverManager.getConnection(url+db,"root","");
                    try{
    PreparedStatement psmnt;
         psmnt = con.prepareStatement("insert into gmailphoto(id,Photo) "+ "values(?,?)");
         psmnt.setInt(1, 9);
         psmnt.setObject(2, is, java.sql.Types.BLOB);
         int s = psmnt.executeUpdate();
           Statement st = con.createStatement();
        try{
            ResultSet rs=st.executeQuery("select photo from gmailphoto where id=9");
            if(rs.next())
              {     //byte[] bytearray = new byte[4096];
                  int size=0;
                File sImage;
    //FIRST TRY
                FileWriter wr=new FileWriter(new File("c:\\imageOutput.jpg"));
                IOUtils.copy(rs.getBlob("photo").getBinaryStream(),wr);
                //SECOND TRY
                BufferedImage bf=ImageIO.read(new ByteArrayInputStream(rs.getBytes("photo")));
                FileOutputStream fout=new FileOutputStream(new File("C:\\imageOut"));
                if(bf!=null)ImageIO.write(bf, "jpg", fout);
                if(wr!=null)
                wr.flush();
                wr.close();
              rs.close();
           }}catch(SQLException e){
                System.out.println(e);
           }Thanks a lot for help

    but i was trying to store it in DB using the following codeThere is no code here that writes to a database. There are two lots of code that write to a file.

  • Not equal is not working

    hi
    i write code in co extension below if (!weight.equals(weight_perc)) is not working how ever if("Core Objective".equals(Coreobjective)) is working here weight & weight_perc both are integers and Core objectives are string.
    public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processFormRequest(pageContext, webBean);
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    OAViewObject vo =(OAViewObject)am.findViewObject("ObjectivesVO");
    if ("Apply".equals(pageContext.getParameter(EVENT_PARAM)))
    String person_id = (new Integer(pageContext.getEmployeeId())).toString();
    pageContext.writeDiagnostics(this,"person_id: "+person_id,OAFwkConstants.STATEMENT);
    String s1 = pageContext.getDecryptedParameter("pObjectiveId");
    pageContext.writeDiagnostics(this,"s1 "+s1,OAFwkConstants.STATEMENT);
    String weight_perc =pageContext.getParameter("Weighting");
    pageContext.writeDiagnostics(this,"weight_perc: "+weight_perc,OAFwkConstants.STATEMENT);
    String objective= pageContext.getParameter("ObjectiveName");
    pageContext.writeDiagnostics(this,"Objective_Name: "+objective,OAFwkConstants.STATEMENT);
    String Coreobjective = objective.substring(0,14);
    pageContext.writeDiagnostics(this,"Coreobjective: "+Coreobjective,OAFwkConstants.STATEMENT);
    String query="select weighting_percent from per_objectives where objective_id ='"+s1+"'";
    String weight = null;
    try
    pageContext.writeDiagnostics(this,"Enters into try block",OAFwkConstants.STATEMENT);
    PreparedStatement ps= am.getOADBTransaction().getJdbcConnection().prepareStatement(query);
    ResultSet rs=ps.executeQuery();
    pageContext.writeDiagnostics(this,"Excute the quiery",OAFwkConstants.STATEMENT);
    while(rs.next())
    weight =rs.getString(1);
    pageContext.writeDiagnostics(this,"weight: "+weight,OAFwkConstants.STATEMENT);
    catch(Exception e)
    e.printStackTrace();
    if("Core Objective".equals(Coreobjective))
    if (!weight.equals(weight_perc))
    pageContext.writeDiagnostics(this,"ENTERS INTO EQUAL CONDITION: ",OAFwkConstants.STATEMENT);
         MessageToken[] errTokens = { new MessageToken("VOLDWEIGHTAGE", weight)};
    throw new OAException("XX_PG", "XXBPTY_COREOBJ_WEIGHT_NOCHANGE", errTokens);
    plz help me.
    Regars,
    sharif.

    Before you do equals check, you should check if any of the value is null or not.
    Both the values are numbers, but you are getting them into strings. So you have to do string compare.
    Or it's easier to get them as numbers and use logical operators as suggested by other fellow experts to compare.
    If you still want to go for Strings here is what you need to do(may be bit cautions here)
    if ((str1!=null || !"".equals(str1))&& (str2!=null || !"".equals(str2)) && str1.equals(str2)){
    Yes both of them are same
    else{
    They are different.
    Regards,
    Peddi.

  • Bean is not worked  in the jsff page

    Hi
    JDeveloper Studio Edition Version 11.1.2.2.0
    I Have a bean for run a jasperreport
    package Reports;
    import javax.faces.event.ActionEvent;
    import sp11.model.apm.clubImpl;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.util.HashMap;
    import java.util.Map;
    import javax.faces.context.FacesContext;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import net.sf.jasperreports.engine.JasperExportManager;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.engine.JasperReport;
    import net.sf.jasperreports.engine.type.WhenNoDataTypeEnum;
    import net.sf.jasperreports.engine.util.JRLoader;
    import net.sf.jasperreports.view.JasperViewer;
    import oracle.adf.model.BindingContext;
    import oracle.adf.model.binding.DCIteratorBinding;
    import oracle.binding.BindingContainer;
    import oracle.jbo.client.Configuration;
    public class CardFrontBean {
    public CardFrontBean() {
    public String runReportAction(){
    DCIteratorBinding rleIter = (DCIteratorBinding)getBindings().get("RealentityIterator");
    String RleId = rleIter.getCurrentRow().getAttribute("RleId").toString();
    BigDecimal ID = new BigDecimal(RleId);
    Map parameter = new HashMap();
    parameter.put("ID", ID);// where ID is a jasper report parameter
    try
    runReport("card_front.jasper", parameter);
    catch (Exception e)
    return null;
    public BindingContainer getBindings(){
    return BindingContext.getCurrent().getCurrentBindingsEntry();
    public ServletContext getContext(){
    return (ServletContext)getFacesContext().getExternalContext().getContext();
    public HttpServletResponse getResponse(){
    return (HttpServletResponse)getFacesContext().getExternalContext().getResponse();
    public static FacesContext getFacesContext(){
    return FacesContext.getCurrentInstance();
    public void runReport(String repPath, java.util.Map param) throws Exception {
    Connection conn = null;
    try
    HttpServletResponse response = getResponse();
    ServletOutputStream out = response.getOutputStream();
    response.setHeader("Cache-Control", "attachment;filename=\"CardFront.pdf\"");
    response.setContentType("application/pdf");
    ServletContext context = getContext();
    InputStream fs = context.getResourceAsStream("/ReportsFolder/" + repPath);
    JasperReport template = (JasperReport) JRLoader.loadObject(fs);
    template.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);
    PreparedStatement statement = null;
    String amDef = "sp11.model.apm.club";
    String config = "clubLocal";
    clubImpl am = (clubImpl)Configuration.createRootApplicationModule(amDef,config);
    statement = am.getDBTransaction().createPreparedStatement("select 1 from dual", 0);
    conn = statement.getConnection();
    JasperPrint print = JasperFillManager.fillReport(template, param, conn);
    //JasperViewer.viewReport(print, false);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JasperExportManager.exportReportToPdfStream(print, baos);
    out.write(baos.toByteArray());
    out.flush();
    out.close();
    FacesContext.getCurrentInstance().responseComplete();
    catch (Exception jex)
    jex.printStackTrace();
    finally
    close(conn);
    public void close(Connection con){
    if (con != null)
    try
    con.close();
    catch (Exception e)
    and a commandButton in the .jsff page
    <af:commandButton id="Realentitycardfront"
    textAndAccessKey="#{nls['REALENTITY_CARDFRONT']}"
    shortDesc="#{nls['REALENTITY_CARDFRONT_HINT']}"
    action="#{CardFront.runReportAction}"/>
    my .jsff page is in a bounded task flow with Use Page Fragments = true
    when i click the button. ........>nothing
    what is the matter
    i read in a post that it is not work in jsff page with page fragmentation
    please help me
    thanks

    One problem is that you write into the output stream from an action method and don't know what's already in the output stream. Once there is one byte written to hte stream (which you can't know from inside the action method) the pdf stream does not behave as you think it would.
    Next thing is that you use createRootApplicationModule but never release it. This will get you out of resources error eventually.
    A better approach would be to put this code in a servlet and stream the report from there. In the servlet you have control over the output stream.
    Check my blog http://tompeez.wordpress.com/2011/12/16/jdev11-1-2-1-0-handling-imagesfiles-in-adf-part-3/ where I show how to serve images from a servlet which can even use the application module pool from the application (no need to use createRootApplicationModule at all). All you have to do is to exchange the part where I get and stream the image data to your needs.
    Timo

  • Selecting a one row from the database is not working

    Hi all I am having a small problem with getting a row from my database to show up. Here is the code for the search that I want to do
                            String item; String columnName; String result; columnName = (String)searchBox.getSelectedItem(); item = searchField.getText().trim(); String tableName = "employee"; if(item == null || item.equals("")){ System.out.println("No Text entered"); }else{ try { result = sql.retrieve_From_Database(columnName, tableName, item); System.out.println(result); } catch (SQLException e1) { sql.displayErrors(e1); }
    Here is the code for the retrieve_From_Database function.
    protected String retrieve_From_Database(String columnName, String tableName, String item) throws SQLException{ ResultSet rs = null; Statement sm = null; sm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = sm.executeQuery("select * from " + tableName + " where " + columnName + " = " + item); result = rs.getString(columnName); if(result == null){ System.out.println("Error in retrieve"); return new String("No results in DB"); }else{ System.out.println(result); return result; } }
    When I run the first code I get an error of SQL Exception: Unknown column 'anthony' in 'where clause'. But yet when I run the query of
    Select * from employee where FirstName = 'anthony'
    within the mysql commandline I get the proper result. So my question is why when running this in the command line do I get the proper result but when running the code I do not?

    jo**** wrote:
    Hi. The problem is clear in the original post. The OP is trying to use PreparedStatement
    parameters to fill out general portions of the SQL query, instead of only data values.
    He is hoping to put in a column name. That will never work. Only data values are settable.
    HTH,
    Joe WeinsteinActually, no. There's no PreparedStatement there at all. It appears that his problem is that, while the working query entered directly in the client is
    Select * from employee where FirstName = 'anthony'the query he's constructing in his code is
    Select * from employee where FirstName = anthonySince there are no quotes around anthony, it's treated as a column name.
    If he had properly used PreparedStatment as suggested in reply 1, that would not be an issue. My guess, however, is that when he claims he's using PS, it's as Tolls suggested a couple of posts ago--he's simply replacing the Statement with a PreparedStatement, but not using the parameters as suggested.
    The wrong thing for OP to do at this point is see my above comment about the quotes and explicitly add them in the query string. The right thing to do, of course, is to actually use PS's parameters.
    Edited by: jverd on Oct 11, 2010 10:08 AM

  • Problem with GenericCatalogDAO  JDBC Resultset using parameters not working

    Hello
    I have a problem with Petstore GenericCatalogDAO. java. The problem is the behaviour of the resultset object when retrieving data from the database.Below are two synareos one that
    works (when) hard coded and one that does not work when parameter values passed into the the result set.
    1. The code the WORKS.
    statement = connection.prepareStatement("select a.productid , name, descn from product a, product_details b
    where a.productid = b.productid and locale= 'en_US' and a.catid = 'FISH' order by name"
    ,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    resultSet = statement.executeQuery();
    resultSet.absolute(1);
    String s = resultSet.getString(1);
    The code that gives me a 'exhausted resultset' error which I think means no results
    String[] parameterValues = new String[] { locale.toString(), categoryID };(For example parameters are 'en_US' and 'FISH')
    statement = connection.prepareStatement("select a.productid , name, descn from product a, product_details b
    where a.productid = b.productid and locale=? and a.catid =? order by name"
    ,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    for (int i = 0; i < parameterValues.length; i++) {
    statement.setString(i + 1, parameterValues[i]);
    resultSet = statement.executeQuery();
    resultSet.absolute(1);
    String s = resultSet.getString(1);
    There is obviously a problem using these named parametevalues with these preparedstatement resultset, Does anybody know anything about this and a fix for it????
    Cheers. Roger

    Which version of PetStore are you using?
    -Larry

  • Jsp:setProperty tag is not working

    hi i am working on project online test system when registering the student i want to use the setProperty tag to set the values from the student form into the approproate bean properties but this tag doesn't work instead i have to set all values of bean by calling the respective setter methods and i am using tomcat as web server.
    i am sending the code as well please help me if u can.
    the html coding for student form is
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>registration of student</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body bgcolor="#677E7E" text="#AC9E6C">
    <table width="75%" border="1" align="center" bordercolor="#677E7E">
    <tr>
    <td><font size="5">STUDENT REGISTRATION FORM</font></td>
    </tr>
    </table>
    <hr>
    <p> </p>
    <form name="student_registration_form" method="post" >
    <script language="JavaScript" >
    function validateField()
              var
                   sos=document.student_registration_form.StartOfSession.selectedIndex,
                   eos=document.student_registration_form.EndOfSession.selectedIndex,
                   deg=document.student_registration_form.Degree.selectedIndex,
                   sem=document.student_registration_form.Smester.selectedIndex,
                   sec=document.student_registration_form.Section.selectedIndex,
                   rol=document.student_registration_form.RollNo.value,
                   pas=document.student_registration_form.Password.value;
    if(sos==0)
                        alert(" \n You Can Not Leave StartOfSession Field Empty");
    else
              if(eos==0)
                        alert("\n You Can Not Leave EndOfSession Field Empty");
              else
              if(deg==0)
                        alert("\n You Can Not Leave Degree Field Empty");
              else
              if(sem==0)
                        alert("\n You Can Not Leave Smester Field Empty");
              else
              if(sec==0)
                        alert("\n You Can Not Leave Section Field Empty");
              else
              if(rol=="")
                        alert("\n You Can Not Leave RollNo Field Empty");          
              else
              if(pas=="")
                        alert("\n You Can Not Leave Password Field Empty");          
              //document.student_registration_form.EndOfSession.value=="" || document.student_registration_form.Degree.value=="" || document.student_registration_form.Section.value=="" || document.student_registration_form.Smester.value=="" || document.student_registration_form.RollNo.value=="" || document.student_registration_form.Password.value=="")
              else
    if(!(sos==0) || !(eos==0) || !(deg==0) ||
              !(sec==0) || !(Smester==0) ||
              !(document.student_registration_form.RollNo.value=="") ||
              !(document.student_registration_form.Password.value=="")
         //document.forms[0].reset();     
    //checking validity of the password field
    var LengthOfRollNo=pas.length;
                   for(i=0;i++;i<LengthOfRollNo )
                        if(!(pas.subString(i,i++)>0))
                                  alert("please enter numaric value in the password field");
                                  return true;
                   document.student_registration_form.submit();
    self.location='StudentRegistration.jsp';
    //return true;
         student_registration_form.StartOfSession.value="";
    student_registration_form.EndOfSession.value="";
    student_registration_form.Degree.value="";
    student_registration_form.Section.value="";
    student_registration_form.Smester.value="";
    student_registration_form.RollNo.value="";
    </script>
    <table width="76%" border="1" align="center" bordercolor="#677E7E">
    <tr>
    <td width="61%"><font size="3">SESSION</font></td>
    <td width="39%">
    <table width="75%" border="1" bordercolor="#677E7E">
    <tr>
    <td><select name="StartOfSession" size="1">
    <option>Start of Session</option>
    <option>2000</option>
    <option>2001</option>
    <option>2002</option>
    <option>2003</option>
    <option>2004</option>
    <option>2005</option>
    <option>2006</option>
    <option>2007</option>
    </select></td>
    <td bordercolor="#677E7E">TO</td>
    <td><select name="EndOfSession" size="1">
    <option>End Of Session</option>
    <option>2001</option>
    <option>2002</option>
    <option>2003</option>
    <option>2004</option>
    <option>20006</option>
    <option>2007</option>
    <option>2008</option>
    <option>2009</option>
    <option>2010</option>
    <option>2011</option>
    <option>2012</option>
    <option>2013</option>
    <option>2014</option>
    </select></td>
    </tr>
    </table></td>
    </tr>
    <tr>
    <td><font size="3">NAME OF DEGREE</font></td>
    <td><select name="Degree" size="1">
    <option>  </option>
              <option>MCS</option>
    <option>BCS</option>
    <option>BBA</option>
    <option>MBA</option>
    <option>MPA</option>
    <option>BSIT</option>
    <option>MSIT</option>
    <option>BBIT</option>
    <option>MSIT</option>
    </select></td>
    </tr>
    <tr>
    <td>SEMESTER </td>
    <td><select name="Smester" size="1">
    <option>   </option>
              <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
    </select></td>
    </tr>
    <tr>
    <td>SECTION</td>
    <td><select name="Section" size="1">
    <option>   </option>
              <option>A</option>
    <option>B</option>
    <option>C</option>
    <option>D</option>
    </select></td>
    </tr>
    <tr>
    <td>ROLL NUMBER (<font size="2">NUMARIC ONLY</font>)</td>
    <td><input type="text" name="RollNo"></td>
    </tr>
    <tr>
    <td>PASSWORD</td>
    <td><input type="password" name="Password"></td>
    </tr>
    </table>
    <table width="12%" border="1" align="center" bordercolor="#677E7E">
    <tr>
    <td><input type="button" name="Submit_bt" value="Submit" onClick="validateField()" /></td>
    </tr>
    </table>
    <p> </p>
    </form>
    <p> </p>
    </body>
    </html>
    and the bean is
    import java.sql.*;
    public class StudentBean
    private String StartOfSession="",EndOfSession="",Degree="",Section="",Smester="",RollNo="",Password="",Status="",LogIn="";
    Connection cn;
    Statement stmt;
    ResultSet rs;
    public StudentBean()
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
    cn=DriverManager.getConnection("jdbc:odbc:intery");
    stmt=cn.createStatement();
    catch(ClassNotFoundException exp)
         System.out.println("class not found while obtaining connection from StudentBean.java");
                   catch(SQLException exp)
                        System.out.println("SQLException araised while obtaining a connection from StudentBean.java");
                   catch(Exception exp)
    System.out.println("exception in obtaining connection from StudentBean.java");
    public String getStartOfSession()
    return StartOfSession;
    public void setStartOfSession(String startofsession)
    StartOfSession=startofsession;
    public String getEndOfSession()
    return EndOfSession;
    public void setEndOfSession(String endofsession)
    EndOfSession=endofsession;
    public String getDegree()
    return Degree;
    public void setDegree(String degree)
    Degree=degree;
    System.out.println("Degree = "+Degree);
    public String getSection()
    return Section;
    public void setSection(String section)
    Section=section;
    public String getSmester()
    return Smester;
    public void setSmester(String smester)
    Smester=smester;
    System.out.println("yar Smesterrrrrr"+Smester+" from StudentBean");
    public String getRollNo()
    return RollNo;
    public void setRollNo(String rollno)
    RollNo=rollno;
    public String getPassword()
    return Password;
    public void setPassword(String password)
    Password=password;
    public String getStatus()
    return Status;
    public void setStatus(String status)
    Status=status;
    public String isRegistered()
    String IsRegistered="";
    LogIn=StartOfSession.concat("-").concat(EndOfSession).concat("-").concat(Degree).concat("-").concat(Section).concat("-").concat(Smester).concat("-").concat(RollNo);
    try
    PreparedStatement ps=cn.prepareStatement("select * from student where username = '"+LogIn+"'");
    rs=ps.executeQuery();
    if(rs.next())
    IsRegistered="registered";
    else
    IsRegistered="notregistered";
    catch(Exception exp)
    IsRegistered="Exception";
    System.out.println(exp+"from isRegistered method of StudentBean.java ");
    return IsRegistered;
    public boolean checkRollNo()
    try
    //rn is used to keep the value of RollNo
    int rn=Integer.parseInt(RollNo);
    catch(Exception exp)
    return false;
    return true;
    public boolean registerStudent()
                   System.out.println("rigisterStudentMethod has been called");
                        LogIn=StartOfSession.concat("-").concat(EndOfSession).concat("-").concat(Degree).concat("-").concat(Section).concat("-").concat(Smester).concat("-").concat(RollNo);
              System.out.println(LogIn);
                   try
              PreparedStatement ps=cn.prepareStatement("insert into student values(?,?,?)");
              ps.setString(1,LogIn);
              ps.setString(2,Password);
              ps.setString(3,"allowed");
              ps.executeUpdate();
              catch(SQLException exp)
    System.out.println(exp+"from StudentBean.java");
    catch(Exception exp)
    System.out.println(exp+"from StudentBean.java");
                                  System.out.println("Exception during insertion of record in student table from StudentBean.java");
                                  return false;
    return true;
    and the jsp page for seting bean property and performing other actions is
    <jsp:useBean id="StudBean" scope="page" class="StudentBean" />
    \\(here <jsp:setPropety name="StudBean" property="*" /> is not working)
    <%
    StudBean.setStartOfSession(request.getParameter("StartOfSession"));
              StudBean.setEndOfSession(request.getParameter("EndOfSession"));
    StudBean.setDegree(request.getParameter("Degree"));
    StudBean.setSmester(request.getParameter("Smester"));
    StudBean.setSection(request.getParameter("Section"));
    StudBean.setRollNo(request.getParameter("RollNo"));
    StudBean.setPassword(request.getParameter("Password"));
    if(StudBean.checkRollNo()==false)
    %>
    <%@ include file="invalid_data_in_rollno_field.htm" %>
    <%
    else
    String IsRegistered=StudBean.isRegistered();
    if(IsRegistered.equals("registered"))
    %>
    <%@ include file="already_registered.htm" %>
    <%
    else
    if (StudBean.registerStudent() && IsRegistered.equals("notregistered") )
    %>
    <%@ include file="successfull_registration.htm" %>
    <%
    else
    %>
    <%@ include file="unsuccessfull_registration_of_student.htm" %>
    <%
    %>
    please tell me where i am making mistake since i have mentioned all the
    form attributes name and the bean attributes name as same.

    I think that all your form parameters must begin with alowercase letters, for example
    startOfSession instead of StartOfSession
    try to rename your selectname paramters.
    Le me know if ti works,
    Giovanni

  • Jsp code is not working after some modification in design why?

    hi,
    I am in the final touch of my course work in jsp.i did all the coding and tested..everything was working properly..after i did some modification in the structure of the page the update query is not working..i dont understand why?
    i am attaching my old page and new page here...plz help me to solve this...
    old page editstudent.jsp
    <html>
    <body>
    <%@ page language="java" import="java.sql.*,java.text.SimpleDateFormat,java.util.Date" %>
    <%
    SimpleDateFormat formatter;
    formatter = new SimpleDateFormat("dd-MM-yyyy");
    String refno=request.getParameter("refno");
         String student=request.getParameter("student");
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con=DriverManager.getConnection("jdbc:odbc:lsmsdsn","","");
         Statement st1=con.createStatement();
    ResultSet rs=st1.executeQuery("select * from sponsordetails where refno='"+refno+"'");
    %>
    <form name=editsponsorform method="POST" action="editsponsor.jsp" >
    <input type="text" name="refno" size="20" value="<%=refno%>"></p>
    <p>Sponsor Name <input type ="text" name="sponsorname" size="50" value="<%=rs.getString(2)%>"></p>
    <p>Sponsor's Address&nbsp<textarea name="sponsorsaddress" rows="5" cols "80" tabindex="10"><%=rs.getString(3)%></textarea></p>
    <p>Sponsor's Phoneno <input type ="text" name="sponsorsphoneno" size="30" value="<%=rs.getInt(4)%>"></p>
    <p>Sponsor's Fax <input type ="text" name="sponsorsfax" size="30" value="<%=rs.getInt(5)%>"></p>
    <input type="submit" name="b1" value="Save & Continue" >
    <input type="Reset" name="b2" value="Cancel "onClick="window.location='home.html'">
    old page editsponsor.jsp
    <html>
    <body>
    <%@ page language="java" import="java.sql.*,java.text.SimpleDateFormat,java.util.*" %>
    <%
    String refno=request.getParameter("refno");
    String sponsorname=request.getParameter("sponsorname");
    String sponsorsaddress=request.getParameter("sponsorsaddress");
    String d=request.getParameter("sponsorsphoneno");
    int sponsorsphoneno=Integer.parseInt(d);
    String d1=request.getParameter("sponsorsfax");
    int sponsorsfax=Integer.parseInt(d1);
    Connection con =null;
    try
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con=DriverManager.getConnection("jdbc:odbc:lsmsdsn","","");
         PreparedStatement st=con.prepareStatement("update sponsordetails set sponsorname= ?,sponsorsaddress=?,sponsorsphoneno=?,sponsorsfax=? where refno=?");
    st.setString(1,sponsorname);
    out.println(sponsorname);
    st.setString(2,sponsorsaddress);
    st.setInt(3,sponsorsphoneno);
    st.setInt(4,sponsorsfax);
    st.setString(5,refno);
    st.executeUpdate();     
         st.executeUpdate();
         out.println("record updated successfully"+"<A HREF='loginhtml.html'>login page</A>.");
    finally {
         try {
              if (con !=null) {
              con.close();
         catch (SQLException se)
         out.println(se.getMessage());
    %>
    </body>
    </html>
    New page editstudent.jsp
    <html>
    <body>
    <%@ page language="java" import="java.sql.*,java.text.SimpleDateFormat,java.util.Date" %>
    <%
    SimpleDateFormat formatter;
    formatter = new SimpleDateFormat("dd-MM-yyyy");
    String refno=request.getParameter("refno");
         String student=request.getParameter("student");
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con=DriverManager.getConnection("jdbc:odbc:lsmsdsn","","");
         Statement st1=con.createStatement();
    ResultSet rs=st1.executeQuery("select * from sponsordetails where refno='"+refno+"'");
    %>
    <form name=editsponsorform method="POST" action="editsponsor.jsp" onSubmit="return validateEditsponsorform()">
    <table width="821" border="1" align="center" bordercolor="#F8F8F8" bgcolor="#F5F5F5">
    <tr>
    <td colspan="6" bgcolor="#CCCCCC"><p class="style6"> </p>
    <p class="style6"> </p>
    <p class="style6"> </p></td>
    </tr>
    <tr>
    <td width="130">Ref No:</td>
    <td width="158">
    <input type="text" name="refno" disabled="true" value="<%=refno%>" />
    </td></tr>
    <tr>
    <td width="130">Sponsor Name</td>
    <td width="158">
    <input type="text" name="sponsorname" value="<%=rs.getString(2)%>"/>
    </td></tr>
    <tr>
    <td>Sponsor's Address:</td>
    <td>
    <textarea name="sponsorsaddress" cols="20" rows="5"><%=rs.getString(3)%></textarea>
    </td></tr>
    <tr>
    <td>Sponsor's Phone No:</td>
    <td>
    <input type="text" name="sponsorsphoneno" value="<%=rs.getInt(4)%>"/>
    </td></tr>
    <tr>
    <td>Sponsor's Fax:</td>
    <td>
    <input type="text" name="sponsorsfax" value="<%=rs.getInt(5)%>" />
    </td></tr>
    <tr>
    <td>
    <input type="submit" name="b1" value="Submit & continue" />
    </td>
    <td><label>
    <input type="reset" name="b2 " value="cancel" onClick="window.location='home.html'" />
    </td>
    </tr>
    </table>
    </form>
    new page editsponsor.jsp
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Edit</title>
    <style type="text/css">
    <!--
    .style2 {
         color: #CC6600;
         font-weight: bold;
         font-size: small;
    .style4 {
         color: #0000CC;
         font-weight: bold;
         font-size: large;
    -->
    </style>
    </head>
    <body bgcolor="#F5F7F4" topmargin="0">
    <%@ page language="java" import="java.sql.*,java.text.SimpleDateFormat,java.util.*" %>
    <div align="center">
    <table width="800" border="0" cellpadding="0" cellspacing="0" bgcolor="#FBFCFF">
    <!--DWLayoutTable-->
    <tr>
    <td height="150" colspan="3" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
    <!--DWLayoutTable-->
    <tr>
    <td width="800" height="139" valign="top"><img src="images/banner copy.jpg" width="800" height="150" /></td>
    </tr>
    </table>
    <%
    String refno=request.getParameter("refno");
    String sponsorname=request.getParameter("sponsorname");
    out.println(sponsorname);//i am getting the values here.............
    String sponsorsaddress=request.getParameter("sponsorsaddress");
    out.println(sponsorsaddress);
    String d=request.getParameter("sponsorsphoneno");
    out.println(d);
    int sponsorsphoneno=Integer.parseInt(d);
    out.println(sponsorsphoneno);
    String d1=request.getParameter("sponsorsfax");
    int sponsorsfax=Integer.parseInt(d1);
    out.println(sponsorsfax);
    Connection con =null;
    try
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con=DriverManager.getConnection("jdbc:odbc:lsmsdsn","","");
    PreparedStatement st=con.prepareStatement("update sponsordetails set sponsorname= ?,sponsorsaddress=?,sponsorsphoneno=?,sponsorsfax=? where refno=?");
    st.setString(1,sponsorname);
    out.println(sponsorname);
    st.setString(2,sponsorsaddress);
    st.setInt(3,sponsorsphoneno);
    st.setInt(4,sponsorsfax);
    st.setString(5,refno);
    st.executeUpdate();
         out.println("record updated successfully"+"<A HREF='loginhtml.html'>login page</A>.");
    finally {
         try {
              if (con !=null) {
              con.close();
         catch (SQLException se)
         out.println(se.getMessage());
    %>
    </body>
    </html>
    the database is not updating...its updating when i am giving values directly to update query..why?help me plzzz..
    thanks in advance

    ashish1234 wrote:
    hi,
    I am in the final touch of my course work in jsp.i did all the coding and tested..everything was working properly..after i did some modification in the structure of the page the update query is not working..i dont understand why?
    i am attaching my old page and new page here...plz help me to solve this...
    the database is not updating...its updating when i am giving values directly to update query..why?help me plzzz..With all that Java code in your JSPs, it doesn't look like you are in the final touch of learning JSP, but just at the beginning. Try to move all that java code into Servlets and JavaBeans. The JSP should be all about display, and nothing else.
    What is your problem? I don't know. All that unformatted code is un-readable. On top of being scriptlet code which is hard enough to read.
    You should search the logs to see if there is an error message hidden in there. That is one of the major problems with putting regular Java code in JSPs, the error messages get hidden, and become near impossible to translate.

  • Select condition not work, possible mistake

    I have simple select like
    String sStatus=req.getParameter("processStatus")==null?"":req.getParameter("processStatus");
    I can get the value of
    sStatus
    but my else is not working, what is the possible mistake?
    if(sStatus.equals("#"))
    Sql+=" and basicStatus=1 order by family_income asc ";                              
    else
    Sql+=" and basicStatus=1 and ProcessStatus='"+sStatus+ "' order by family_income asc ";                         
    I try sql in db db like and basicStatus=1 and ProcessStatus='"New' order by family_income asc      it work fine, so??
    Thank you

    Hi jverd,
    thank you fot the reply, but before I only nedd to executeQuery my sql once, but, if I use PreparedStatement, then I have to
    executeQuery as many as the conditions I have , any way, right now I change my code to
    String Sql="SELECT * FROM student2 as s, student_financial_info2 as f where s.student_id=f.student_id ";
                    //search for Id, so we don't care about status and how many row in one page
                    if (university_ID !=""){                   
                              Sql+=" and s.student_id=? order by family_income asc ";
                              ps = conn.prepareStatement(Sql);
                              ps.setString(1,university_ID );
                              ps.executeUpdate();
                              connectionPool.returnConnection(conn);
                    //for group search
                    else{
                       if(search.equals("All")){              
                            if(basicStatus.equals("basicStatus"))                     
                                 Sql+=" and ProcessStatus=? and basicStatus=? order by family_income asc ";
                                          Sql+=" limit " + currentRow + ",100"; 
                                          ps = conn.prepareStatement(Sql);
                                             ps.setString(1, FStatus);
                                             ps.setInt(2,1);
                                             ps.executeUpdate();
                                             connectionPool.returnConnection(conn);        
                       //for department search
                        else{
                            if(basicStatus.equals("basicStatus")){
                              Sql+=" and faculty =? and ProcessStatus=? and basicStatus=? order by family_income asc";
                              ps = conn.prepareStatement(Sql);
                              ps.setString(1,  search);
                               ps.setString(2, FStatus);
                               ps.setInt(3,1);
                               ps.executeUpdate();
                                connectionPool.returnConnection(conn);}
                            else{
                              Sql+=" and faculty ='"+search+ "' order by family_income asc";
                              ps = conn.prepareStatement(Sql);
                              ps.setString(1,  search);
                              ps.executeUpdate();                 
                                connectionPool.returnConnection(conn);
                    }// out elseI get error on String Sql="SELECT * FROM student2 as s, student_financial_info2 as f where s.student_id=f.student_id ";
              //search for Id, so we don't care about status and how many row in one page
              if (university_ID !=""){                   
                        Sql+=" and s.student_id=? order by family_income asc ";
                        ps = conn.prepareStatement(Sql);
                        ps.setString(1,university_ID );
                        ps.executeUpdate();
                        connectionPool.returnConnection(conn);
              //for group search
              else{
              if(search.equals("All")){              
                   if(basicStatus.equals("basicStatus"))               
                        Sql+=" and ProcessStatus=? and basicStatus=? order by family_income asc ";
    *                    Sql+=" limit " + currentRow + ",100";*
    *                    ps = conn.prepareStatement(Sql);*
    *                                   ps.setString(1, FStatus);*
    *                                   ps.setInt(2,1);*
    *                                   ps.executeUpdate();*
    *                                   connectionPool.returnConnection(conn);*
              //for department search
              else{
                   if(basicStatus.equals("basicStatus")){
              Sql+=" and faculty =? and ProcessStatus=? and basicStatus=? order by family_income asc";
                   ps = conn.prepareStatement(Sql);
                   ps.setString(1, search);
                        ps.setString(2, FStatus);
                        ps.setInt(3,1);
                        ps.executeUpdate();
                        connectionPool.returnConnection(conn);}
                   else{
                   Sql+=" and faculty ='"+search+ "' order by family_income asc";
                   ps = conn.prepareStatement(Sql);
                   ps.setString(1, search);
                   ps.executeUpdate();           
                        connectionPool.returnConnection(conn);
              }// out else
    I got error on the blod part JDBC error:Parameter index out of range (1 > number of parameters, which is 0).
    java.sql.SQLException: Parameter index out of range (1 > number of parameters, w
    hich is 0). How com the index is start on 0?
    Thank you

  • SQL UPDATE does not work

    Hey Guys,
    I have an update sql query which does not work with PreparedStatement object. Heres the code snippet:
    PreparedStatement pstmt;
    int numUpd;
    pstmt = con.prepareStatement(
    "UPDATE item_articles SET dataFile=? WHERE itemID=?");
    con.setAutoCommit(false);
    pstmt.setBinaryStream(1,fis,(int)file.length());
    pstmt.setInt(2,item.id);
    numUpd = pstmt.executeUpdate();
    con.commit();
    What I am doing here is that setBinaryStream(...) will upload a file into the DB. The query executes, theres no exception thrown, but my table shows empty field for the file. Note, there are no exceptions thrown from this query.
    If I do the same thing for an INSERT statement, it works. The file gets into the DB. So , the file is there on disk, and theres no problem with it. Just that it does not work with UPDATE.....any clues ???
    thanks
    Askar

    I think UPDATE commands dont work well with blobs.
    I use to select the register with a ResultSet, then get a BLOB Object from the column.
    So you can use a OutputStream to Upload your data.

  • PrepareStatement does not work

    Hi,
              I am using prepareStatement in Javacode.
              The database is Oracle 8.1.6.3.
              The column type is number(10).
              I am trying to update one column in this table by passing bind variable in.
                   sb.append("update tnp_trackable ");
                             sb.append("set poll_int=");
                             sb.append(pollInt);
                             sb.append(", update_time=sysdate ");
                             sb.append(" where tnp_track_id=?");
                             PreparedStatement pst = conn.prepareStatement(sb.toString());
              pst.setLong(1, trackID);
                                  pst.executeUpdate();
              ChecK db, no updates happen. But if I change to createStatement, it works.
              Could you help me figure out WHY
              Thanks
              Stacy
              

    Learning how to program by using JDBC and JSP is going to be very difficult.
    It does not work.It tells you why if you print the exception.
    1. int TestNumber=123;
    2. String sqlqry = "select ... from timeTable where EventID = TestNumber";
    The literal 'TestNumber' in lines 1 and 2 have absolutely NOTHING to do with each other. In line one it is a java variable. In line two it is an sql identifier which has no meaning and thuse it will cause an exception.

Maybe you are looking for

  • For loop in jstl

    Hi i'm wondering what is the format of a for loop in jstl. for example: my for loop: for(int i = 0; i< stringArray.Length(); i++){ i++; thanks

  • What should be needed for cost reports to be activated in Business Content?

    Hi experts,   I am completely new to Business Content so sorry if I ask a silly question. Currently we are trying to migrate custom fixed queries to queries from Cubes in Business Content, because the company has growed in the past years.   Our first

  • Powebook:  no 'home' or 'end' keys..

    hi, I'm working with a very long MS Word document, but because on the powerbook keyboard there are no "home" or "end" keys, I can't find how to quickly navigate to beginning or end of the document (as described here, http://www.internet4classrooms.co

  • Why are the books from Lauren Dohner gone?

    Recently, I tried to look and see if there were any new Laurann Dohner books in iTunes, and I see that all the books are no longer there even those I had bought previously. Can someone explain to me why they're gone?

  • How to read sort sequence and other properties of a specification in Cg02 .

    hello , i need to update the specification properties in CG02 basing on sort sequence  for hazards and mariane pollutant of a specification. do we have any standard Bapi or Fm to read the properties of Specification . thanks for your help Ananta