Problem deleting rows using JDBC

Hi,
I have a problem with the following code listed below. I am attempting to delete a user's details from a SQLServer db based on the user selected from a combobox. The code given below is just a section and relates to a JButton I have on the application that performs the delete command.
public void deleteButton_actionPerformed(ActionEvent e) {
try{
String opName = (String)userNameBox.getSelectedItem();
String deleteQuery = "select * from Operator where OperatorName = " + "'"+opName+"'";
//Load Database Driver Class
Class.forName(JDBC_DRIVER);
//Establish a connection to the Database
connection = DriverManager.getConnection(DATABASE_URL);
//Create Select statement for returning all usernames to the combobox
statement2 = connection.createStatement(java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
//dQuery.setString(1,opName);
resultSet = statement2.executeQuery(deleteQuery);
while (resultSet.next()){
resultSet.deleteRow();
catch(Exception exception){
exception.printStackTrace();}
To explain the code, to begin with a String holds the value of the selected field of the combobox i have in my app. I have the SQL select statement the using this variable as the where clause.
The usual connection and statement objects are declared etc and then the query is executed. Within the While loop I then attempt to delete the row that the query has retrieved for me. However this results in the following error.
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Invalid attribute/option identifier
Any help is much appreciated.
Thanks
Alan

Thanks for the reply. I understand your comment about
using the delete statement and it seems I am making
an obvious error. However I was using the select
statement to generate a resultSet object with which I
can delete elements from. Hence the reason for the
use of the select statement.This is brain dead, the classic newbie mistake. The database vendor has optimized their code more than you ever will in making those deletes, so use their code. Not only will they do it faster than you will, but you'll save yourself (n+1) network roundtrips (1 for the SELECT, 1 for each DELETE you issue). Better to learn SQL and use a WHERE clause to do it on the database side.
You have however solved the problem I had with
directly executing the delete statement as an SQL
String. I was using the following statement:
String deleteQuery = "select * from Operator where
OperatorName = " + "'"+opName+"'";
The wildcard character is not required and it was
this that gave me problems and made me look to using
a select query and deleting results from a
resultSet.Sounds like you need a SQL book. I recommend "SQL For Smarties".
%

Similar Messages

  • Problem deleting rows from a JTable

    I've got an editable JTable and a button outside that deletes rows selected by a user from the model. The problem is that if the user has clicked on an editable cell in the table, while rest of the information in that row is deleted, the entry in the editable cell remains. So even though the entry has been deleted from the model, the JTable does not update correctly. I am using a custom editor/renderer for the editable cells.
    So it appears that I need to get my custom editor to release, i.e., stop editing on demand, so I can reset the information on the entire row properly.
    Any ideas how I can do so ?
    Thanks, Bhishma

    Thanks that worked perfectly ! Full points assigned.
    In case the above link stops working the solution that worked for me was using a client property as below.
    jTable1.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    Ciao.
    Edited by: Bhishma on Dec 20, 2008 7:53 PM

  • Handling million rows using jdbc

    approximately how much time would it take to use jdbc and do a simple data import from an oracle database having 500 million rows?

    Without a lot more information my answer would be too long.
    It is likely that something is wrong with the design of a project if it involves bring 500 million records into a running java application.
    Using a 1000 byte record size it would take 19 hours just to move the data over a 100mbit ethernet connection.

  • Better approach for deleting rows using trigger or procedure

    Hi,
    Please suggest which option is better for deleting rows from table trigger or procedure and why?
    In datawarehousing and OLTP DB's.
    Edited by: user6040008 on Nov 2, 2012 4:51 AM

    Hi,
    Please suggest which option is better for deleting rows from table trigger or procedure and why?
    In datawarehousing and OLTP DB's.
    Edited by: user6040008 on Nov 2, 2012 4:51 AM

  • Add Column Delete  in report, How to delete row using this delete Option

    Hi Friends,
    i have a report ,iwant to add an option DELETE in last column.When i click on DElete then respective id sholund be deleted.
    My Table Is
    CREATE TABLE  "DUMY_FILE"
       (     "ID" NUMBER,
         "NAME" VARCHAR2(500),
         "FILE_OBJ_ID" NUMBER,
         "MIME_TYPE" CLOB,
         "DOC_SIZE" NUMBER,
         "BLOB_CONTENT" BLOB,
         "DESCRIPTION" VARCHAR2(500),
         "UPLOAD_DATE" CHAR(25)
    How can i do this.
    Thanks
    Edited by: 805629 on Nov 16, 2010 11:51 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Trent,
    Thanks for you suggestions. .. Let me explain my problem a little better ...
    I have a report that lists fields associated with a report ... I have a delete icon which deletes a row and removes it from the underlying table ... however, I am trying to implement a Before header process which runs a pl/sql process that checks if the selected field is the last field in the report ... if so, I want a confirmation dialog to pop up ... if they click cancel .. then the deletion is aborted, else the field is deleted (which triggers other status changes).
    Based on this logic if there is a way to implement this based on your suggestion I would appreciate it ...
    Here is the process I was trying to use .... but the I have a few issues with this approach
    declare
    -- cursor to check if this is the last field
    cursor fld_cnt is
    select count(*) from prm_ptnr_rpt_fields
    where report_uid = :P22_REPORT_UID;
    num_flds number;
    msg varchar2(300);
    begin
    open fld_cnt;
    fetch fld_cnt into num_flds;
    If num_flds > 1 then
    delete from prm_ptnr_rpt_fields
    where report_uid = :P22_REPORT_UID
    and field_user_key = :P9_DELETED_FLD;
    commit;
    :P9_DELETED_FLD := NULL;
    msg := :P9_FIELD_NAME || ' Field Excluded From Report' ;
    apex_application.g_print_success_message := msg;
    else
    htp.p('<script type="text/javascript">');
    htp.p('
    var r=confirm("This is the last field included in this report .. \n Deleting it will Inactivate the report and remove it from schedule (if scheduled) ...\n Do you want to proceed?");
    if (r==true)
    {      delete from prm_ptnr_rpt_fields 
    where report_uid = :P22_REPORT_UID
    and field_user_key = :P9_DELETED_FLD;
    :P9_DELETED_FLD := NULL;
    commit;
    msg := :P9_FIELD_NAME || ' Field Excluded From Report' ;
    update prm_ptnr_rpts
    set report_status = 'INCOMPLETE',
    active_report = 'N'
    where report_uid = :P22_REPORT_UID;
    msg := msg || ' and Report Status changed to INCOMPLETE';
    apex_application.g_print_success_message := msg;
    htp.p('}else {
    alert("Delete Action Aborted");
    htp.p('</script>');
    End if;
    Close fld_cnt;
    end;
    a) Even if I click cancel ... the field still gets deleted ...
    b) :P9_DELETED_FLD is the id for the selected field ... I am setting it on the link attributes which places it on the URL ... I would rather user javascript (but not exactly sure how).
    Thanks,
    Gerald
    Edited by: user5459177 on Feb 22, 2011 2:45 PM

  • Problem finding row using findbykey()

    Could someone give me any hints as to why when I call viewObject.findByKey(keyx, -1) it returns null yet viewObject.getRow(keyx) returns the correct row?
    Cheers
    Shaun Field

    Hi Steven
    I use the following code to construct my key for the View/Entity object that has the primary key values AppName, Release, and Status:
    FTReleaseNoDomain releaseNo = new FTReleaseNoDomain( request.getSession().getAttribute("ReleaseNo").toString());
    NameValuePairs attributeList = new NameValuePairs();
    attributeList.setAttribute("AppName", request.getSession().getAttribute("ReleaseAppName"));
    attributeList.setAttribute("Release", releaseNo);
    attributeList.setAttribute("Status", request.getSession().getAttribute("ReleaseStatus"));
    Key key = vo.createKey(attributeList);
    I then try calling the following:
    Row row = viewObject.getRow(key);
    Row rowArray[] = viewObject.findByKey(key, -1);
    The variable row has some value where as rowArray[0] causes an ArrayOutOfBounds exception(ie it's empty).
    I have tried changing the variable releaseNo to a string but that doesn't give me a correct key thus causing the getRow() to fail.
    I have found that I'm able to get a result for findbyKey() if I use the key that I get from the row found using getRow(). eg Key rowKey = viewObject.getRow(key).getKey();
    The version of Jdeveloper/BC4J I'm using is 9.0.3.3
    Cheers
    Shaun Field

  • Problem deleting photos using ios7 on ipad 2

    I updated my iPad 2 with no problems. I then went to the apple photo app, selected a photo which correctly put a checkmark on it, but the trash can icon stayed greyed out, making it impossible to delete that photo. selecting multiple photos results in the same problem. Please log this as a bug and fix.

    Ok, more details.
    1. When in the iOS 7 Photo app you tap Photo button in the bottom toolbar.
    2. Then you tap Select in the top right Navbar
    3. Then find a photo which is NOT in the Photo-stream and NOT in the Camera Roll. I have a bunch of these for some reason after updating to iOS 7. These photos will get a checkmark, but will not turn the trash can blue.
    4. You can then select a photo that IS IN Photo-stream. It will also get a checkmark and the counter will display (2), and the trash can will turn Blue.
    5. You can then tap the blue trash can. The Photo-stream selected photo gets deleted BUT the photo the selected photo that is NOT in Photo-stream and NOT in camera roll IS Still There!
    I think the issue is that these photos that show under Photo but don't appear in the Camera Roll or Photo-Stream are "Orphans". So the real issue is how do I "adopt" them and get them into either the Camera Roll or zphto-strem? Still ths appears to be a bug that needs an Ape fix.

  • Button column delete row

    Hi guys i have a problem i have a code to delete row from datagridview following:
     If DataGridViewX1.SelectedRowsRows.Count > 0 Then
                DataGridViewX1.Rows.Remove(DataGridViewX1.SelectedRows(0))
            Else
                MessageBox.Show("DUMB SELECT A ROW TO DELETE")
            End I f
    but when i am using this code on button of button column its not working bcz this code wants a row to be selected. i want to delete row using a button in button column.
     Plz Help
    Thank You.

    Hi guys i have a problem i have a code to delete row from datagridview following:
     If DataGridViewX1.SelectedRowsRows.Count > 0 Then
                DataGridViewX1.Rows.Remove(DataGridViewX1.SelectedRows(0))
            Else
                MessageBox.Show("DUMB SELECT A ROW TO DELETE")
            End I f
    but when i am using this code on button of button column its not working bcz this code wants a row to be selected. i want to delete row using a button in button column.
     Plz Help
    Thank You.
    Hello,
    You could get that task done inside its cellcontent_click event, because we could get the rowindex of that row which we clicked. You could refer to the sample below.
    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    Dim senderGrid = DirectCast(sender, DataGridView)
    If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso
    (e.RowIndex >= 0 And e.RowIndex < senderGrid.RowCount - 1) Then
    If MsgBox("Would you like to remove this row?", MsgBoxStyle.YesNo, "Delete Row") = MsgBoxResult.Yes Then
    senderGrid.Rows().RemoveAt(e.RowIndex)
    End If
    End If
    End Sub
    Regards.
    Carl
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Problem in using JDBC Execute commands(Update & Delete Only) with af:Table

    HI Everyone,
    I have one issue with Updating and Deleting Row Data using JDBC Execute commands.
    Suppose In My Application i have two pages, in Page 1 I have Two Command Buttons(Delete and Save) and One Input TextBox to write the String to be stored in the Database. and Page 2 where the result Table is shown and table is binded with a ViewObject, Now When User Types some String in InTB and click Save then By Programmatically I'm searching, that string is already present in database or not, if it is already exist then Save button converts in Update button and instead of inserting it allows user to Update the String already exist in database.
    Everything is working fine but the problem comes when i put those all buttons on the same page where result table is present.After putting all things on the same page and When i click save button to insert new String it is Successfully inserting but when any of other action is performed like updating or Deleting the existing one.. then my application just hanged and then nothing I able to do.
    Please Help me to understand this problem and give me the solution for this..
    Thanks
    Fizzz...

    Hi frank,
    Thanks to reply me...
    I'm refreshing table's iterator on each command button's action to reflect the changed result... and i'm sorry i mentioned two pages in my project.. actually these are two forms in the same page..which conditionally changed its renderer properties.. its working fine when only one form is renderred and the otherside when both are rendered then it is not working.
    Hope this change will help you to understand the problem.. if something else you are looking for then please tell me..
    Thanks
    Fizzz...

  • How to delete rows in the target table using interface

    hi guys,
    I have an Interface with source as src and target as tgt both has company_code column.In the Interface i need like if a record with company_code already exists we need to delete it and insert the new one from the src and if it is not availble we need to insert it.
    plz tell me how to achieve this?
    Regards,
    sai.

    gatha wrote:
    For this do we need to apply CDC?
    I am not clear on how to delete rows under target, Can you please share the steps to be followed.If you are able to track the deletes in your source data then you dont need CDC. If however you cant - then it might be an option.
    I'll give you an example from what im working on currently.
    We have an ODS, some 400+ tables. Some are needed 'Real-Time' so we are using CDC. Some are OK to be batch loaded overnight.
    CDC captures the Deletes no problem so the standard knowledge modules with a little tweaking for performance are doing the job fine, it handles deletes.
    The overnight batch process however cannot track a delete as its phyiscally gone by the time we run the scenarios, so we load all the insert/updates using a last modified date before we pull all the PK's from the source and delete them using a NOT EXISTS looking back at the collection (staging) table. We had to write our own KM for that.
    All im saying to the OP is that whilst you have Insert / Update flags to set on the target datastore to influence the API code, there is nothing stopping you extending this logic with the UD flags if you wish and writing your own routines with what to do with the deletes - It all depends on how efficient you can identify rows that have been deleted.

  • How to release row lock by using jdbc

    hi, currently we are using jdbc to create a connection and create a row lock , is there anyway to release the row lock? right now i am using resultset.close(), but this cause me problem since it release other resultset's row lock too. please help.

    hi, from your post, i understood that u know how to do row locking..
    How was it done ??
    I'm currently looking for answer to do row locking in Microsoft Access...
    These are the SQL stmt i've done without success..
    SELECT * FROM BSPerson WITH UPDLOCK WHERE ID = 'P001';
    SELECT * FROM BSPerson WHERE ID = 'P001' FOR UPDATE;
    Both stmt having error........
    Please help !
    A miliion thanks....

  • Delete  row  internal  bank  problem

    Hi,
    i  wasn't  able  to   delete   row  of   my  internal  bank,  despite  i   delete  this  bank   in  my   BP  account and   in  all  payment  method.
    Also   i   delete   all  the  information  in  internal  banck  account  (  branch,  count  number,  iban,etc)  but  when  i  delete  the  row  the  system  give  me  this  messagge  error
    bank account is currently in use and therefore can not be eliminated  705-20 
    i   currently  use   2007A   SP  01   patch  level  7
    how  can  i  resolve  this   problem?  thanks  a  lot

    Hi,
    thanks   a   lot,   but   this  bank   is  not   linked   to  any  one  field  in  Sap  B1
    1)  in  initial  details  there   isn't
    2)   in  payment   methods  there  isn't 
    3)  in  registry  BP  there   isn't
    where  can  i   has   to   find   it????
    By  copy  espress  i   had  copied  all  payment  methods  (  with  this  bank),  and  after   i   deleted   this   payment   methods  without   using  this  payment  method   in  anyone   Sap  b1  documents....and here the strange thing

  • Problem with delete command through JDBC

    hi all,
    I have the following code in a Java program
    try
    DriverManager.registerDriver
    (new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection(
    "jdbc:oracle:thin:@localhost:1521:orcl", "airport", "airport");
    catch (SQLException ex)
    ex.printStackTrace();
    Every statement works fine except the delete command. When i try to execute this statement:
    stmt = conn.createStatement();
    stmt.executeUpdate("DELETE FROM distances");
    the program stalls. The table "distances" is owned by the user airport and this sql command works fine when I execute it in SQL+. The problem occurs when I try to execute a delete command through JDBC.
    Can anyone help me?
    Thanks...

    It seems that the problem ocuurs only when there are pending transactions.Correct. There are uncommitted INSERT/UPDATE/DELETEs on the table. Readers never block writers, thus having opened SELECT cursors on the table is not a problem. You writer process must be blocked by another writer process. (assuming of course no JDBC thin driver error - of which I've heard rumours there are or were quite a few - not using thin JDBC myself, thus cannot comment on whether these rumours are valid or not)
    What I would think a bit concerning is that one application trashing a table (deleting all the data) while other applications/users are busy changing data in that table. Why are they changing data that will be immediately trashed after they have committed their transactions? Surely they are wasting time and resources all around (user-side and server-side) by doing work that will be immediately invalidated? This kind of points to me to a database or application design problem.

  • Problems deleting current row

    Hello,
    I have got the following problem. I have got a table with data from my database. And a dataprovider to fetch the data from my rowset. I have got a button in each row of this table where i can get details or delete the corresponding row.
    But when i click delete he wont delete the row correct. After a while i realised that the always fetch the same row. I dont understand why because i took the same code as it was used in the tutorial. For control i made a variable to remember the id of the fetched row but it wont change after the first "delete". Can somebody tell me why he wont change the value?
    public String l�schen_action() {
    try {
    RowKey rowKey = tableRowGroup1.getRowKey();
    int id = getSessionBean1().getMaxappid().parseInt(applikationDataProvider.getValue("APPID", rowKey).toString(), 10);
    getSessionBean1().setTemp(id);
    if(rowKey != null && applikationDataProvider.canRemoveRow(rowKey)){
    applikationDataProvider.removeRow(rowKey);
    applikationDataProvider.commitChanges();
    applikationDataProvider.refresh();
    } catch (Exception e) {
    log("Fehler beim L\366schen des Eintrags", e);
    error("Exception deleting row: " + e);
    } // end try catch
    return null;
    Thanks in advance for help
    Acinonyx

    Try this and see if that helps
    Rowkey currentRowKey = (RowKey) getBean("currentRow");
    - Winston
    http://blogs.sun.com/roller/page/winston?catname=Creator

  • JTable &  AbstractTableModel(Delete row problem)

    Hi!!
    I have used AbstractTableModel in my JTable.In case of multiple rows, i want to delete rows from interface as well as from database. As removeRow method is absent in AbstractTableModel.so DefaultTableModel has been used by casting but CastClassException throws. Here is Partial code(tried in many ways).Plz help me to solve the problem.
    void jButtonCancel_actionPerformed(ActionEvent e) {
    try{
    jTable1.setModel(myModel); //jtable is object of JTable and myModel is of Abstract TableModel           
    DefaultTableModel model=((DefaultTableModel)jTable1.getModel());
    int row=jTable1.getSelectedRow();
    if(row>=0){
    model.removeRow();
    jTable1.revalidate();
    model.fireTableDataChanged();
    System.out.println("Rows Delete");
    catch(Exception sq){
    sq.printStackTrace();
    sq.getMessage();

    Hmm...
    A bit of studying java awaits you.
    Anyway.
    Your class:
    public class MyModel extends AbstractTableModel
      // Do various sorts of coding here
    }Is not an instance of DefaultTableModel, so, if you try to cast your model to a DefaultTableModel it will throw an exception since the conversion is impossible.
    Recomended solution:
    Add a remove method for your class MyModel that does the following:
    public void removeRow(int row)
      // data removed
      // fire removed data event
    }Then instead of casting to DefaultTableModel, cast it to 'MyModel' and call the method 'removeRow'.
    When it comes to inheritance and casting you can always cast an object to any of it's superclasses or any of the interfaces it supplies or it's superclasses suppplies. You can not cast an object to a instance of which it has no relation with.
    In you example, your table model class extends the abstract table model but it does not extend the DefaultTableModel. An instance of your class can be casted to AbstractTableModel and so can an DefaultTableModel because they are both subclasses from AbstractTableModel. They can also be casted to TableModel since all of these implement the interface needed to fullfill TableModel's specification.
    If you cast a DefaultTableModel instance to TableModel you can not try to cast it upwards to something the instance wasn't from the beginning.
    Example:
    DefaultTableModel dtm = new DefaultTableModel();
    // When you do casting uppwards, there is no need for paranthesis
    TableModel tm = dtm;
    // You can easily later on cast this back to what is what or to any step
    // in between
    DefaultTableModel stillSameModel = (DefaultTableModel)tm;
    // You can not however cast to something the instance never was
    // Row below will cause an compile error:
    JComboBox jb = (JComboBox)dtm;
    // This since JComboBox can never be an superclass to the DefaultModel
    // More dangerous errors that can't be catched until runtime is the
    // one you made. Ie: I do what could be an valid cast
    MyModel mm = (MyModel)tm;
    // Since MyModel is an TableModel and tm refers to an TableModel,
    // this casting is approved by the compiler.
    // It will on the other hand throw an ClassCastException when run since
    // the variable tm contains an instance of DefaultTableModel which
    // is not an MyModel instance.Recomended that you read up on inheritance and basic OO.
    Regards,
    Peter Norell

Maybe you are looking for

  • IMac 3.06 GHz Intel Core 2 Duo with 12gb of RAM running very very slow.

    My late 2010 iMac 3.06 GHz Intel Core 2 Duo with 12gb of ram is running very slow. It takes a very long for the computer to boot with the desktop taking ages to fully load. Applications are also taking an unholy amount of time to load with the spinni

  • Dbms_job.submit procedure called from Forms

    Folks, Since the DBMS_JOB.SUBMIT cannot be executed directly within a form, I created a simple procedure on the database which makes the call to DBMS_JOB.SUBMIT as follows: FUNCTION web_newsletter_submit_job(p_letter_id NUMBER) RETURN NUMBER IS v_job

  • Third party remittance simulation document

    Hi Guys, When i open third party remittance simulation posting document in PCP0 and when double click on vendor to see the details of payments it shows me following error. "An explanation of some or all document lines is not possible". Here is the de

  • Produced items not creating transfer orders automatically

    configuration is set in such a way that. transfer reqirements and TO are created and confirmed automatically for the items produced inhouse. its not hapeening so.its creating TR and I have to in to Tr and create a To and confirm it. what configuratio

  • ITunes/QuickTime on Windows 7 - HD Playback Stutter

    I can't seem to properly playback HD video files in iTunes or QuickTime without the whole file stuttering. System Specs: Core i7-920 6GB RAM 80GB Intel SSD 1TB Western Digital Black HDD nVidia GTX 460 768MB Windows 7 64-bit iTunes 10.4.1.10 Quicktime