Problem on delete statement in JSP

org.apache.jasper.JasperException: An exception occurred processing JSP page /proj/AdminLog.jsp at line 130
127: Driver Driverrs3 = (Driver)Class.forName(MM_Conn_DRIVER).newInstance();
128: Connection Connrs3 = DriverManager.getConnection(MM_Conn_STRING,MM_Conn_USERNAME,MM_Conn_PASSWORD);
129: PreparedStatement Statementrs3 = Connrs3.prepareStatement("DELETE *  FROM database.credentials  WHERE UserId = 16");
130: ResultSet rs3 = Statementrs3.executeQuery();
root cause
javax.servlet.ServletException: java.sql.SQLException: Can not issue data manipulation statements with executeQuery().i also tried executeUpdate(); but it is still not working.

is it possible to reference a javascript variableinside a JSP block?
what i am trying to do is to delete all rows that are checked from the list on button clickNo it is not possible.
The button has to submit the form, and then you use request.getParameter() to find out which checkboxes were checked.
The best approach is to give all your checkboxes the same name, and the value being the id you want to delete.
eg
<input type="checkbox" name="deluser" value="42">
<input type="checkbox" name="deluser" value="69">
<input type="checkbox" name="deluser" value="666">
then in your java/servlet code
// using a prepared statement in this case is more efficient. 
// Can reuse the same statement multiple times.
PreparedStatement stmt = connect.prepareStatement("delete from credentials where UserId = ?";
// retrieve the selected checkboxes.
String[] selectedIds = request.getParameterValues("delUser");
// check to see if any were checked
if (selectedIds != null){
  // iterate over all userids marked for deletion
  for (int i=0; i<selectedIds.length; i++){
    int idToDelete = Integer.parseInt(selectedIds);
stmt.setInt(1, idToDelete);
stmt.execute();
Cheers,
evnafets

Similar Messages

  • Problem with delete statement

    Hi there, I have created this code below.  The select statement works, however the delete statement does not work.
    DECLARE
    @CategoryASVARCHAR(255)
    DECLARE
    @NameASVARCHAR(255)
    DECLARE
    @Name1ASVARCHAR(255)
    DECLARE
    @ParentTypeAsint
    SET
    @Category='General
    Building Data'
    SET
    @Name='Purchase
    Date'
    SET
    @Name1='Purchase
    Cost'
    Set
    @ParentType=20
    Select
    *fromtbAttributeValueA
    Join
    tbAttributeTemplateDefinitionLinkATDLONATDL.AttributeTemplateDefinitionLinkID=A.AttributeTemplateDefinitionLinkID
    Join
    tbAttributeTemplateDefinitionATDONATD.AttributeTemplateDefinitionID=ATDL.AttributeTemplateDefinitionID
    JOIN
    tbAttributeSetSONS.AttributeSetID=ATDL.LinkedParentID
    Where
    S.ParentType=@ParentType
    AND
    S.Name=@Category
    AND
    ([email protected]=@Name1)
    AND
    A.Value=0
    delete
    fromtbAttributeValueA
    Join
    tbAttributeTemplateDefinitionLinkATDLONATDL.AttributeTemplateDefinitionLinkID=AttributeTemplateDefinitionLinkID
    Join
    tbAttributeTemplateDefinitionATDONATD.AttributeTemplateDefinitionID=ATDL.AttributeTemplateDefinitionID
    JOIN
    tbAttributeSetSONS.AttributeSetID=ATDL.LinkedParentID
    Where
    S.ParentType=@ParentType
    AND
    S.Name=@Category
    AND
    ([email protected]=@Name1)
    AND
    A.Value=0
    The delete statement fails on the first join.     Incorrect Syntax near 'A'.  What am I doing wrong?  As I have only changed the select * to delete.  So therefore does this mean I need to put the delete statement into a
    sql sub query? Or is there another way of doing this?

    Try this:
    DELETE FROM tbAttributeValue
    FROM tbAttributeTemplateDefinitionLink ATDL
    JOIN tbAttributeValue t
    ON ATDL.AttributeTemplateDefinitionLinkID = t. AttributeTemplateDefinitionLinkID
    JOIN tbAttributeTemplateDefinition ATD
    ON ATD.AttributeTemplateDefinitionID = ATDL.AttributeTemplateDefinitionID
    JOIN tbAttributeSet S
    ON S.AttributeSetID = ATDL.LinkedParentID
    WHERE S.ParentType = @ParentType
    AND S.NAME = @Category
    AND ( ATD.NAME = @Name
    OR ATD.NAME = @Name1 )
    AND A.Value = 0

  • Receiver side JDBC - Problem with DELETE statement

    Hi,
    I have a scenario where in I need to delete legacy system data every time I run the interface before inserting new rows.
    I tried with stored procedure, by writing statement:
    Truncate <table>.
    Insert <records> into <table>.
    But problem is stored procedure is called every time so when run for the second time it deletes the 1st entry before placing 2nd. This way only last record is being fetched :(.
    Any suggestions?
    Thanks in Advance,
    Rohan.

    hi rohan,
    check the below blog , i think it solves your issue
    JDBC Adapter execution mode Chained or Unchained
    JDBC Adapter execution mode Chained or Unchained ??
    reward points if helpfull
    regards
    kummari

  • Problems with StoredProcedures that use INSERT/DELETE statements

    Hello
    I am using Hyperion Intelligence explorer 8.5, and the database source is a MS SQL Server 2000 source connected via ODBC.
    I have this problem: when I use, in a Query section, a stored procedure that (in its code) uses only SELECT statements I get the result of the query in the Results section, but when I use a storedprocedure that does some work (and executes INSERT or DELETE or other SQL statements) and ends executing a SELECT statement in order to return data to the caller Hyperion hangs.
    I mean: first I select the stored procedure (Query\StoredProcedure... menù, than I start it using the Process command in Hyperion.
    If the storedproc contains only SELECT statements I get the results, but if it contains INSERT or DELETE (and the last statement is a SELECT) Hyperion does not return any data and if I try to repeat the Process command I get an error that tells "the connection is busy with results from another hstmt".
    Before you ask me if the stored procedure works correctly, I can confirm this because the storedproc was tested and returns the correct data if used with the db manager application.
    Any suggestions? Did you ever use (successfully )storedprocedures that process data (by INSERT or DELETE statements) and then return the result with a SELECT statement?
    Thank you for your help

    Hi Chris,
    Could you please tell us in which version of IR
    Hyperion is not going to support Stored
    Procedures....
    Regards,
    ManmohanManmohan,
    Did you even read what I just wrote? This is NOT happening. Stroed Procedures are an important part of the Intelligence Product, Oracle is continuing to enhance and support this functionality. I work for Oracle, I worked for Hyperion, and for Brio before that, so believe me when I tell you this.
    Chris (whoever he is) is gving out incorrect information in this regard. His suggestion of the workaround for the original issue is completely accurate, but as I added, it was in issue that has been corrected as of 8.5 Service Pack 2, so even the workaround is not required as long as you've upgraded. (Note that some versions of 9.x also will require the workaround due to the timing of the releases overlapping.)
    Thanks.
    Larry Johnson

  • Problem : SQL Server Delete Statement vs Oracle Delete Statement

    Hi,
    I am currently involved in a SQL Server - Oracle Migration effort and I have hit a roadblock on one of the queries.
    I have created two tables named DUMMY and DUMMY1 in MSDE with the same structure :-
    CREATE TABLE DUMMY
         CLIENT_ID                                             INT,
         NME                                                   VARCHAR(80),
         BATCH_ID                                              INT,
         CATALOG_NAME                                          VARCHAR(50),
         DATA_SOURCE                                           VARCHAR(50)
    GOI have a DELETE statement that deletes from the two tables, by selecting common data using Joins:-
    DELETE  DUMMY
    FROM      DUMMY src
            JOIN
         DUMMY1 dst 
              ON
                  src.batch_id = dst.batch_id 
              AND src.catalog_name = dst.catalog_name 
              AND src.data_source = dst.data_source
         WHERE
                   src.batch_id     = 1
              AND      src.catalog_name = '1'
                  AND      src.data_source  = '1'Now, I have created the same Tables ( DUMMY and DUMMY1 ) in Oracle :-
    CREATE TABLE DUMMY
         CLIENT_ID                                             NUMBER(5),
         NME                                                      VARCHAR2(80),
         BATCH_ID                                             NUMBER(10),
         CATALOG_NAME                                  VARCHAR2(50),
         DATA_SOURCE                                     VARCHAR2(50)
    )I have written a Delete statement to mimic the fucntionality in this manner :-
    DELETE FROM 
              DUMMY 
    WHERE
                   client_id,
                   nme,
                   batch_id,
                   catalog_name,
                   data_source
              IN
                   SELECT *
                   FROM
                        DUMMY  src
                                           JOIN 
                        DUMMY1  dst 
                             ON
                                  src.batch_id = dst.batch_id
                             AND      src.catalog_name = dst.catalog_name
                             AND      src.data_source = dst.data_source
                        WHERE
                                  src.batch_id = 1
                             AND      src.catalog_name= '1'
                             AND      src.data_source = '1'
              )However, I keep getting this error whe I try to test it :-
    ORA-06550: line 1, column 89:
    PL/SQL: ORA-00913: too many values
    Can you please help me modify the query to simulate the same functionality as the orignial SQL Server Query ?
    Thanks,
    Sandeep

    There is probably a mismatch between the number of columns.
    Try this * Not Tested *
    DELETE FROM 
              DUMMY 
    WHERE
                   client_id,
                   nme,
                   batch_id,
                   catalog_name,
                   data_source
              IN
                   SELECT      src.client_id,
                   src.nme,
                   src.batch_id,
                   src.catalog_name,
                   src.data_source
                   FROM
                        DUMMY  src
                                           JOIN 
                        DUMMY1  dst 
                             ON
                                  src.batch_id = dst.batch_id
                             AND      src.catalog_name = dst.catalog_name
                             AND      src.data_source = dst.data_source
                        WHERE
                                  src.batch_id = 1
                             AND      src.catalog_name= '1'
                             AND      src.data_source = '1'
              );

  • Problem connecting oracle database to jsp pages using Apache Tomcat server 8.0

    Well...I tried too many things..googled so many times..but still could not find solution to my problem.
    I use windows 8 Enterprise Edition(if this has to do something with the problem)
    Oracle 11.2.0
    Apache Tomcat server 8.0
    JDK 1.7
    My oracle is installed in the D: drive and tomcat in c:. i copied the ojdbc6.jar file from oracle to lib directory of tomcat server.
    Then i set  CLASSPATH in environment variables as "C:\Program Files\Apache Software Foundation\Tomcat 8.0\lib\ojdbc6.jar" in system variables
    My path variable is set as "C:\Program Files\Java\jdk1.7.0_02\bin".
    My program is as follows in notepad:
    <%@ page import="java.sql.*" %>
    <html>
    <body>
    <%
    Connection conn;
    Statement st;
    ResultSet rs;
    try{
    new oracle.jdbc.driver.OracleDriver();
    String dbURL="jdbc:odbc:oracle:thin:@localhost:1521:XE";
    String userId="system";
    String pwd="moon";
    conn=DriverManager.getConnection(dbURL,userId,pwd);
    st=conn.createStatement();
    rs= st.executeQuery("SELECT * FROM login");
    while(rs.next())
    System.out.println(rs.getString(1)+""+rs.getString(2));
    catch(Exception e){}
    %>
    </body>
    </html>
    I get too many errors then
    eroors
    org.apache.jasper.JasperException: An exception occurred processing JSP page /page2.jsp at line 14
    11: String userId="system";
    12: String pwd="moon";
    13:
    14: conn=DriverManager.getConnection(dbURL,userId,pwd);
    15: st=conn.createStatement();
    16:
    17: rs= st.executeQuery("SELECT * FROM login");
    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    root cause
    javax.servlet.ServletException: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:905)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:834)
         org.apache.jsp.page2_jsp._jspService(page2_jsp.java:102)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
         org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    Nothing solved this problem.

    >> Nothing solved this problem.
    Can't fix a problem 'till an actual problem is identified.
    >> ODBC Driver Manager ... Data source name not found
    That appears to be ODBC drivers looking for a DSN (Data Set Name). If it wants a DSN, the DSN has to be specified in the code, and the DSN has to be configured in the windows host ODBC applet. So that is at least two squirrels to get in the right tree before moving forward. A ...host:...[port:]SID|service name are some of the bits needed in a jdbc connect string, and that is in no way related to DSNs. A Whole Different Animal. If it wants a DSN that might be what needs to go in the URL bit.
    And ODBC setups can be confusing, especially if an x64 OS is in the mix- if that is the case there are two different ODBC configuration applets, one for x64 the other for x86, and if one gets as far as talking to an actual database it might toss an architecture error. Only way to fix that "problem" is *delete* the ODBC DSN and then run the correct (maybe the x86) ODBC config utility, and set up the DSN. Again.

  • Problem with READ Statement in the field routine of the Transformation

    Hi,
    I have problem with read statement with binary search in the field routine of the transformation.
    read statement is working well when i was checked in the debugging mode, it's not working properly for the bulk load in the background. below are the steps i have implemented in my requirement.
    1. I selected the record from the lookuo DSO into one internal table for all entried in source_packeage.
    2.i have read same internal table in the field routine for each source_package entry and i am setting the flag for that field .
    Code in the start routine
    select source accno end_dt acctp from zcam_o11
    into table it_zcam
    for all entries in source_package
    where source = source_package-source
         and accno = source_package-accno.
    if sy-subrc = 0.
    delete it_zcam where acctp <> 3.
    delete it_zcam where end_dt initial.
    sort it_zcam by surce accno.
    endif.
    field routine code:
    read table it_zcam with key source = source_package-source
                                                 accno  = source_package-accno
                                                 binary search
                                                 transportin no fields.
    if sy-subrc = 0.
    RESULT  = 'Y'.
    else.
    RESULT = 'N'.
    endif.
    this piece of code exist in the other model there its working fine.when comes to my code it's not working properly, but when i debug the transformation it's working fine for those accno.
    the problem is when i do full load the code is not working properly and populating the wrong value in the RESULT field.
    this field i am using in the report filter.
    please let me know if anybody has the soluton or reason for this strage behaviour.
    thanks,
    Rahim.

    i suppose the below is not the actual code. active table of dso would be /bic/azcam_o1100...
    1. is the key of zcam_o11 source and accno ?
    2. you need to get the sortout of if endif (see code below)
    select source accno end_dt acctp from zcam_o11
    into table it_zcam
    for all entries in source_package
    where source = source_package-source
    and accno = source_package-accno.
    if sy-subrc = 0.
    delete it_zcam where acctp 3.
    delete it_zcam where end_dt initial.
    endif.
    sort it_zcam by surce accno.
    field routine code:
    read table it_zcam with key source = source_package-source
    accno = source_package-accno
    binary search
    transportin no fields.
    if sy-subrc = 0.
    RESULT = 'Y'.
    else.
    RESULT = 'N'.
    endif.

  • Missing privilege - DELETE statement in procedure

    Hello experts,
    I am facing a problem for my procedure. I am not able to active the procedure if I use DELETE statement in the produce. When I use only selects, it is working fine. The SYSTEM user has access to the schema with full rights, including DELETE.
    PROCEDURE "SYSTEM"."DEV_COL.procedures::FI" ( )
      LANGUAGE SQLSCRIPT
      SQL SECURITY INVOKER
      DEFAULT SCHEMA UXX790
      AS
    BEGIN
      Write your procedure logic
    -- SELECT vbeln
    --count(*)
      DELETE
      from vbapold
      where erdat < ADD_days(now(), -1700);
    END;
    Did anybody had the same issue? I run HANA rev70.
    BR
    Tamas

    Hi Tamas
    if this is a repository procedure user _SYS_REPO has to have the DELETE privilege with grant option as well.
    - Lars

  • Delete Statement Exception Handling

    Hi guys,
    I have a problem in my procedure. There are 3 parameters that I am passing into the procedure. I am matching these parameters to those in the table to delete one record at a time.
    For example if I would like to delete the record with the values ('900682',3,'29-JUL-2008') as parameters, it deletes the record from the table but then again when I execute it with the same parameters it should show me an error message but it again says 'Deleted the Transcript Request.....' Can you please help me with this?
    PROCEDURE p_delete_szptpsr_1 (p_shttran_id IN saturn.shttran.shttran_id%TYPE,
    p_shttran_seq_no IN saturn.shttran.shttran_seq_no%TYPE,
    p_shttran_request_date IN saturn.shttran.shttran_request_date%TYPE) IS
    BEGIN
    DELETE FROM saturn.shttran
    WHERE shttran.shttran_id = p_shttran_id
    and shttran.shttran_seq_no = p_shttran_seq_no
    and trunc(shttran_request_date) = trunc(p_shttran_request_date);
    DBMS_OUTPUT.PUT_LINE('Deleted the Transcript Request Seq No (' || p_shttran_seq_no || ') of the Student (' || p_shttran_id ||') for the requested date of (' || p_shttran_request_date ||')');
    COMMIT;
    EXCEPTION WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('Error: The supplied Notre Dame Student ID = (' || p_shttran_id ||
    '), Transcript Request No = (' || p_shttran_seq_no || '), Request Date = (' || p_shttran_request_date || ') was not found.');
    END p_delete_szptpsr_1;
    Should I have a SELECT statement to use NO_DATA_FOUND ???

    A DELETE statement that deletes no rows (just like an UPDATE statement that updates no rows) is not an error to Oracle. Oracle won't throw any exception.
    If you want your code to throw an exception, you'll need to write that logic. You could throw a NO_DATA_FOUND exception yourself, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      RAISE no_data_found;
    END IF;If you are just going to catch the exception, though, you could just embed whatever code you would use to handle the exception in your IF statement, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      <<do something about the exception>>
    END IF;In your original code, your exception handler is just a DBMS_OUTPUT statement. That is incredibly dangerous in real production code. You are relying on the fact that the client has enabled output, that the client has allocated a large enough buffer, that the user is going to see the message, and that the procedure will never be called from any piece of code that would ever care if it succeeded or failed. There are vanishingly few situations where those are safe things to rely on.
    Justin

  • Problem in Update statement using Execute Immediate

    Hi All,
    I am facing problem in update statement.
    I am creating dynamic sql and use "execute immediate" statement to execute a update statement.
    But it is not updating any thing there in the table.
    I have created a query like :
    update_query='Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
    Execute immediate update_query using V_Id;
    commit;
    But it is not updating the table.
    I have a question , is execute immediate only does insert and delete?
    Thanks
    Ashok

    SQL> select * from t;
                     TID P
                     101 N
    SQL> declare
      2     V_Id          number := 101;
      3     Table_Name    varchar2(30) := 'T';
      4     update_query  varchar2(1000);
      5  begin
      6     update_query := 'Update '|| Table_Name ||' t set t.process_status =''Y'' where t.tid=:A';
      7     Execute immediate update_query using V_Id;
      8     commit;
      9  end;
    10  /
    PL/SQL procedure successfully completed.
    SQL> select * from t;
                     TID P
                     101 Y                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Problem in delete adjecent duplicates

    Hi All,
    i have a problem in delete adjacent duplicate in an internal table .
    when  i use it i want that the records which are getting doubled to be removed
    but i also want that if the value in that field is empty for which i am comparing , to be ignored means i dont want the records
    to be deleted in which the field value is empty for which i am comparing.
    snippet of my code
    delete ADJACENT DUPLICATES FROM xkomv COMPARING KSCHL.
    so if theere is no value in KSCHL THAT RECORD NOT TO BE DELETED .
    waiting for your reply..
    Thanks in advance

    Try the following,
    "delete ADJACENT DUPLICATES FROM xkomv COMPARING KSCHL.
    Before using the above statement do the following,
    u201C decalare a temporary table for u2018xkomvu2019 say u2018t_xkomvu2019, and copy the data.
    Refresh t_xkomv[].
    t_xkomv[] = xkomv[].
    Delete t_xkomv where KSCHL <> u2018  u2018.
    Delete xkomv where KSCHL =  u2018  u2018.
    u201C Sort xkomv and then use delete adjacent duplicates.
    And after this append data from t_xkomv to xkomv.
    Hope it helps you,
    Regards,
    Abhijit G. Borkar

  • Problem in deleting the message after reading

    Hi
    I m having some problem to delete the message after reading.
    i read the FAQ, and there is only one question regarding to delete that i have tried but its not working
    As my application required that message should be deleted after the processing.
    Please help me out asap
    Thank in advance.

    now here is the protocol trace from starting to the end point
    with the settings of
    session.setDebug(true);
    and
    folder.close(true);
    POP3: connecting to host "172.xx.xx.xx", port 110
    S: +OK Microsoft Exchange Server 2003 POP3 server version 6.5.6944.0 (xxxxx.xyz.com) ready.
    C: USER test1
    S: +OK
    C: PASS Password
    S: +OK User successfully logged on.
    C: STAT
    S: +OK 1 548
    Total messages = 1
    New messages = 0
    ================================
    C: TOP 1 0
    S: +OK
    Received: from yyyyyy ([172.xx.xx.xx]) by xxxxx.xyz.com with Microsoft SMTPSVC(6.0.3790.3959);
         Thu, 11 Sep 2008 12:21:14 +0530
    Message-ID: <3373112.1221115884647.JavaMail.284528@yyyyyy>
    From: [email protected]
    To: [email protected]
    Subject: testing
    Mime-Version: 1.0
    Content-Type: text/plain
    Content-Transfer-Encoding: 7bit
    Return-Path: [email protected]
    X-OriginalArrivalTime: 11 Sep 2008 06:51:14.0500 (UTC) FILETIME=[C8892840:01C913DA]
    Date: 11 Sep 2008 12:21:14 +0530
    C: LIST 1
    S: +OK 1 548
    ------------STARTING LINE------------
    MESSAGE #1:
    From: [email protected]
    To: [email protected]
    Subject: testing
    SendDate: Thu Sep 11 12:21:14 IST 2008
    CONTENT-TYPE: text/plain
    This is plain text
    ------------TEXT------------
    C: RETR 1
    S: +OK
    Received: from yyyyyy ([172.xx.xx.xx]) by xxxxx.xyz.com with Microsoft SMTPSVC(6.0.3790.3959);
         Thu, 11 Sep 2008 12:21:14 +0530
    Message-ID: <3373112.1221115884647.JavaMail.284528@yyyyyy>
    From: [email protected]
    To: [email protected]
    Subject: testing
    Mime-Version: 1.0
    Content-Type: text/plain
    Content-Transfer-Encoding: 7bit
    Return-Path: [email protected]
    X-OriginalArrivalTime: 11 Sep 2008 06:51:14.0500 (UTC) FILETIME=[C8892840:01C913DA]
    Date: 11 Sep 2008 12:21:14 +0530
    ------------TEXT------------
    ******************MESSAGE ENDING LINE*****************
    C: QUIT
    S: +OK Microsoft Exchange Server 2003 POP3 server version 6.5.6944.0 signing off.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Verification on delete statement

    Hi
    i need a verification on delete statement and am trying to execute this delete using prepareStatement and through parameter passing
    the code is given below.plz do let me know the problem with the statement
    =============================================================
    public int delete(String tableName,String empName){
              int n=0;
              System.out.println("Starting!!!delete");
              try{
                   /*stmnt=con.createStatement();
                   stmnt.executeUpdate("delete from Employees where Name= 'jaggu'");*/
                   stmt=con.prepareStatement("delete from ? where Name = ? ");
                   stmt.setString(1, tableName);
                   stmt.setString(2, empName);
                   n=stmt.executeUpdate();
              System.out.println("Deletion Done!!!");
              }catch(Exception e){
                   System.out.println("Error on deletion :"+e);
              return n;
    ===========================================================
    the error being displayed is:
    Error on deletion :java.sql.SQLException: Syntax error or access violation, message from server: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' where Name = ''' at line 1"
    PLZ DO LET ME KNOW WHAT IS WRONG HERE!!!

    yes tat was the problem and now i got it rectified.. for more dynamisation u can use the following code. If so u can delete any row based on the column value from any table...plz tell whether its looking fine or not:
         public int delete(String tableName,String empName){
              int n=0;
              System.out.println("Starting!!!delete");
              try{
                   stmt=con.prepareStatement("delete from "+tableName+" where name = ?");
                   stmt.setString(1, empName);
                   n=stmt.executeUpdate();
              System.out.println("Deletion Done!!!");
              }catch(Exception e){
                   System.out.println("Error on deletion :"+e);
              return n;
         }

  • Problem Displaying out Data in JSP

    can anyone have a look at my code? i got some problems to display it in jsp when i run it with eclipse. can anyone help me on this?? did my java bean declared wrongly? thanks...
    this is my java file
    package com;
    import java.io.File;
    import com.db4o.Db4o;
    import com.db4o.ObjectContainer;
    import com.db4o.ObjectSet;
    import org.jfree.chart.*;
    import org.jfree.data.general.*;
    public class StoreData{
         private static final long serialVersionUID = 1L;
         private final static String filename = "C:\\CountryPieChart.yap";
         public static void main(String[] args){
              //Delete the existing file
              new File(filename).delete();
              ObjectContainer db=Db4o.openFile(filename);
              try {
                   StoreAllData();
                   retrieveAllData();
              } finally{
                   db.close();          //Close the database
         public static void StoreAllData() {
              //Delete the existing file
              new File(filename).delete();
              ObjectContainer db = Db4o.openFile(filename);
              //Add data to the database
              CountryPeople countryName_1 = new CountryPeople("Malaysia", 100);
              CountryPeople countryName_2 = new CountryPeople("New Z", 200);
              CountryPeople countryName_3 = new CountryPeople("UK", 300);
              CountryPeople countryName_4 = new CountryPeople("Thailand", 400);
              CountryPeople countryName_5 = new CountryPeople("Singapore", 50);
              //set the value to database
              db.set(countryName_1);
              db.set(countryName_2);
              db.set(countryName_3);
              db.set(countryName_4);
              db.set(countryName_5);
         public static void retrieveAllData() {
              //Open db
              ObjectContainer db = Db4o.openFile(filename);
              //Retrieve via empty object
              CountryPeople cName = new CountryPeople(null, 0);
              ObjectSet result = db.get(cName);
              DefaultPieDataset dataset = new DefaultPieDataset();
              //retrieve the data from database
              while(result.hasNext()) {
                   CountryPeople obj = (CountryPeople) result.next();
                   dataset.setValue(obj.getName(), obj.getValue());
                   //System.out.println(result.next());
              //Create pie chart
              JFreeChart chart = ChartFactory.createPieChart(
                        "Sample Chart",
                        dataset,     
                        true,
                        true,
                        false);
              try {
                   //save the pie chart as JPEG file
                   ChartUtilities.saveChartAsJPEG(new File("C:\\CountryPieChart.jpg"), chart, 500, 300);
              } catch(Exception e) {
                   System.out.println("Problem for creating chart");
    and this is my jsp file
    <jsp:useBean id="myStoreData" class="com.StoreData" scope="page"></jsp:useBean>
    <html>
    <head><title>Testing Displaying</title>
    </head>
    <body>
    <b>Testing Display Page</b>
    <img src="<jsp:getProperty name="myStoreData" property="getFileName" /> /">
    </body>
    </html>

    <img src="<jsp:getProperty name="myStoreData" property="getFileName" /> /">
    property="getFileName": There isnt such a property available in your bean.

  • Problem of deletion of rows in jtable, table refreshing too

    Hi,
    I have a table with empty rows in the beginning with some custom properties( columns have fixed width...), later user would be adding to the rows to this table and can delete, I've a problem while deleting the rows from table,
    When a selected row is deleted the model is also deleting the data but the table(view) is not refreshed.
    Actually i'm selecting a cell of a row, then hitting the delete button.
    So the model is deleting the information, but i'm not able to c the fresh data in table( especially when the last cell of last row is selectd and hit the delete button, i am getting lots of exception)
    Kindly copy the below code and execute it, and let me know,
    * AuditPanel.java
    * Created on August 30, 2002, 3:05 AM
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.Vector;
    * @author yaman
    public class AuditPanel extends javax.swing.JPanel {
    // These are the combobox values
    private String[] acceptenceOptions;
    private Vector colNames;
    private Color rowSelectionBackground = Color.yellow;
    private int rowHeight = 20;
    private int column0Width =70;
    private int column1Width =96;
    private int column2Width =327;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    /** Creates new form AuditPanel */
    public AuditPanel() {
    public void renderPanel(){
    initComponents();
    public String[] getAcceptenceOptions(){
    return acceptenceOptions;
    public void setAcceptenceOptions(String[] acceptenceOptions){
    this.acceptenceOptions = acceptenceOptions;
    public Vector getColumnNames(){
    return colNames;
    public void setColumnNames(Vector colNames){
    this.colNames = colNames;
    public Vector getData(){
    Vector dataVector = new Vector();
    /*dataVector.add(null);
    dataVector.add(null);
    dataVector.add(null);
    return dataVector;
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
    jPanel2 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jPanel1 = new javax.swing.JPanel();
    jTable1 = new javax.swing.JTable();
    setLayout(new java.awt.GridBagLayout());
    setBorder(new javax.swing.border.EmptyBorder(0,0,0,0));
    jPanel2.setLayout(new java.awt.GridBagLayout());
    jPanel2.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0));
    jButton1.setText("Add");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.ipadx = 8;
    gridBagConstraints.insets = new java.awt.Insets(0, 1, 5, 0);
    gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
    jPanel2.add(jButton1, gridBagConstraints);
    jButton2.setText("Delete");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
    jPanel2.add(jButton2, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
    add(jPanel2, gridBagConstraints);
    jPanel1.setLayout(new java.awt.GridBagLayout());
    jPanel1.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED, Color.black, Color.gray) );
    jTable1.setModel(new javax.swing.table.DefaultTableModel(getData(), getColumnNames()));
    // get all the columns and set the column required properties
    java.util.Enumeration enum = jTable1.getColumnModel().getColumns();
    while (enum.hasMoreElements()) {
    TableColumn column = (TableColumn)enum.nextElement();
    if( column.getModelIndex() == 0 ) {
    column.setPreferredWidth(column0Width);
    column.setCellEditor( new ValidateCellDataEditor(true) );
    if( column.getModelIndex() == 1) {
    column.setPreferredWidth(column1Width);
    column.setCellEditor(new AcceptenceComboBoxEditor(getAcceptenceOptions()));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    //column.setCellRenderer(new AcceptenceComboBoxRenderer(getAcceptenceOptions()));
    if( column.getModelIndex() == 2 ) {
    column.setPreferredWidth(column2Width); // width of column
    column.setCellEditor( new ValidateCellDataEditor(false) );
    jScrollPane1 = new javax.swing.JScrollPane(jTable1);
    jScrollPane1.setPreferredSize(new java.awt.Dimension(480, 280));
    jTable1.setMinimumSize(new java.awt.Dimension(60, 70));
    //jTable1.setPreferredSize(new java.awt.Dimension(300, 70));
    //jScrollPane1.setViewportView(jTable1);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
    jPanel1.add(jScrollPane1, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    add(jPanel1, gridBagConstraints);
    // set the row height
    jTable1.setRowHeight(rowHeight);
    // set selection color
    jTable1.setSelectionBackground(rowSelectionBackground);
    // set the single selection
    jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    // avoid table header to resize/ rearrange
    jTable1.getTableHeader().setReorderingAllowed(false);
    jTable1.getTableHeader().setResizingAllowed(false);
    // Table header font
    jTable1.getTableHeader().setFont( new Font( jTable1.getFont().getName(),Font.BOLD,jTable1.getFont().getSize() ) );
    jButton1.setMnemonic(KeyEvent.VK_A);
    // action of add button
    jButton1.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent){
    // If a button press is the trigger to leave a JTable cell and save the data in model
    if(jTable1.isEditing() ){
    //System.out.println("table is edition ");
    String text=((javax.swing.text.JTextComponent)jTable1.getEditorComponent()).getText();
    jTable1.setValueAt(text,jTable1.getSelectedRow(),jTable1.getSelectedColumn()) ;
    jTable1.getCellEditor().cancelCellEditing();
    // find out total available rows
    int totalRows = jTable1.getRowCount();
    int cols = jTable1.getModel().getColumnCount();
    if( jTable1.getModel() instanceof DefaultTableModel ) {
    ((DefaultTableModel)jTable1.getModel()).addRow(new Object[cols]);
    int newRowCount = jTable1.getRowCount();
    // select the first row
    jTable1.getSelectionModel().setSelectionInterval(newRowCount-1,newRowCount-1);
    jButton2.setMnemonic(KeyEvent.VK_D);
    // action of Delete button
    jButton2.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent){
    int totalRows = jTable1.getRowCount();
    // If there are more than one row in table then delete it
    if( totalRows > 0){
    int selectedOption = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete this audit row?","Coeus", JOptionPane.YES_NO_OPTION);
    // if Yes then selectedOption is 0
    // if No then selectedOption is 1
    if(0 == selectedOption ){
    // get the selected row
    int selectedRow = jTable1.getSelectedRow();
    System.out.println("Selected Row "+selectedRow);
    if( selectedRow != -1 ){
    DefaultTableModel dm= (DefaultTableModel)jTable1.getModel();
    java.util.Vector v1=dm.getDataVector();
    System.out.println("BEFOE "+v1);
    v1.remove(selectedRow);
    jTable1.removeRowSelectionInterval(selectedRow,selectedRow);
    System.out.println("After "+v1);
    }else{
    // show the error message
    JOptionPane.showMessageDialog(null, "Please Select an audit Row", "Coeus", JOptionPane.ERROR_MESSAGE);
    } // end of initcomponents
    class AcceptenceComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public AcceptenceComboBoxRenderer(String[] items) {
    super(items);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    super.setBackground(rowSelectionBackground);
    } else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    // Select the current value
    setSelectedItem(value);
    return this;
    class AcceptenceComboBoxEditor extends DefaultCellEditor {
    public AcceptenceComboBoxEditor(String[] items) {
    super(new JComboBox(items));
    } // end editor class
    public class ValidateCellDataEditor extends AbstractCellEditor implements TableCellEditor {
    // This is the component that will handle the editing of the
    // cell value
    JComponent component = new JTextField();
    boolean validate;
    public ValidateCellDataEditor(boolean validate){
    this.validate = validate;
    // This method is called when a cell value is edited by the user.
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int rowIndex, int vColIndex) {
    if (isSelected) {
    component.setBackground(rowSelectionBackground);
    // Configure the component with the specified value
    JTextField tfield =(JTextField)component;
    // if any vaidations to be done for this cell
    if(validate){
    //tfield.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC,4));
    tfield.setText( ((String)value));
    // Return the configured component
    return component;
    // This method is called when editing is completed.
    // It must return the new value to be stored in the cell.
    public Object getCellEditorValue() {
    return ((JTextField)component).getText();
    // This method is called just before the cell value
    // is saved. If the value is not valid, false should be returned.
    public boolean stopCellEditing() {
    String s = (String)getCellEditorValue();
    return super.stopCellEditing();
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    }//end of ValidateCellDataEditor class
    public static void main(String args[]){
    JFrame frame = new JFrame();
    AuditPanel auditPanel = new AuditPanel();
    frame.getContentPane().add(auditPanel);
    auditPanel.setAcceptenceOptions(new String[]{"Accepted", "Rejected", "Requested"} );
    java.util.Vector colVector = new java.util.Vector();
    colVector.add("Fiscal Year");
    colVector.add("Audit Accepted");
    colVector.add("Comment" );
    auditPanel.setColumnNames( colVector);
    auditPanel.renderPanel();
    frame.pack();
    frame.show();

    Hi,
    I've got the solution for it. As when the cursor is in cell of
    a row and hit the delete button, the data in that cell is not saved,
    So i'm trying to save the data first into the model then firing the action event by doing this ..
    jButton2.addActionListener( new ActionListener(){       
    public void actionPerformed(ActionEvent actionEvent){           
    // If a button press is the trigger to leave a JTable cell and save the data in model
    if(jTable1.isEditing() ){                   
    String text=((javax.swing.text.JTextComponent)jTable1.getEditorComponent()).getText();
    jTable1.setValueAt(text,jTable1.getSelectedRow(),jTable1.getSelectedColumn()) ;
    jTable1.getCellEditor().cancelCellEditing();
    // HERE DO THE DELETE ROW OPERATION
    <yaman/>

Maybe you are looking for