Efficient Way of Inserting records into multiple tables

Hello everyone,
Im creating an employee application using struts framework. One of the functions of the application is to create new employees. This will involve using one web form. Upon submitting this form, a record will be inserted into two separate tables. Im using a JavaBean (Not given here) between the JSP page and the Java file (Which is partly given below). Now this Java file does work (i.e. it does insert a record into two seperate tables).
My question is, is there a more efficient way of doing the insert into multiple tables (in terms of performance) rather than the way I've done it as shown below? Please note, I am using database pooling and MySQL db. I thought about Batch processing but was having problems writing the code for it below.
Any help would be appreciated.
Assad
package com.erp.ems.db;
import com.erp.ems.entity.Employee;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.ArrayList;
public class EmployeeDAO {
     private Connection con;
     public EmployeeDAO(Connection con) {
          this.con = con;
     // METHOD FOR CREATING (INSERTING) A NEW EMPLOYEE
     public void create(Employee employee) throws CreateException {
          PreparedStatement psemployee = null;
          PreparedStatement psscheduleresource = null;
          String sqlemployee = "INSERT INTO employee (FIRSTNAME,SURNAME,GENDER) VALUES (?,?,?)";
          String sqlscheduleresource = "INSERT INTO scheduleresource (ITBCRATE,SKILLS) VALUES (?,?)";
          try {
               if (con.isClosed()) {
                    throw new IllegalStateException("error.unexpected");
                        // Insert into employee table
               psemployee = con.prepareStatement(sqlemployee);
               psemployee.setString(1,employee.getFirstName());
               psemployee.setString(2,employee.getSurname());
               psemployee.setString(3,employee.getGender());
                        // Insert into scheduleresource table
               psscheduleresource = con.prepareStatement(sqlscheduleresource);
               psscheduleresource.setDouble(1,employee.getItbcRate());
               psscheduleresource.setString(2,employee.getSkills());
               if (psemployee.executeUpdate() != 1 && psscheduleresource.executeUpdate() != 1) {
                    throw new CreateException("error.create.employee");
          } catch (SQLException e) {
               e.printStackTrace();
               throw new RuntimeException("error.unexpected");
          } finally {
               try {
                    if (psemployee != null && psscheduleresource != null)
                         psemployee.close();
                         psscheduleresource.close();
               } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException("error.unexpected");
     }

Hi ,
U can use
set Auto Commit function here ..
let it be false first
and when u do with u r all queries ..
make it true
this function take boolean values
i e helful when u want record to be inserted in all or not at all..
Hope it helps

Similar Messages

  • Inserting records into multiple tables

    Just thinking ahead, and trying to get my head around the
    next stage of my database project.
    At the moment I have the following tables :
    Candidates
    Candidate_ID (autonumber)
    Name (text)
    1, Iain
    2, Fi
    3, Rob
    Vacancies
    Vacancy_ID (autonumber)
    Vacancy (text)
    1, Cartographer
    2, Gardener
    3, Occupational therapist
    4, Web designer
    5, Recruitment manager
    Profiles
    Profile_ID (autonumber)
    Profile (text)
    1, Map making
    2, Web design
    3, Gardening
    4, Hand therapy
    5, Recruitment
    6, Aviation
    7, Sport
    8, Travel
    VacancyProfiles
    Vacancy_ID (number)
    Profile_ID (number)
    1,1
    1,2
    4,2
    2,3
    3,4
    5,5
    5,6
    CandidateProfiles
    Candidate_ID (number)
    Vacancy_ID (number)
    1,1
    1,2
    1,7
    1,8
    2,3
    2,4
    2,8
    3,5
    3,6
    3,7
    and from there created two queries
    CandidatesQuery
    SELECT Candidates.Candidate_ID, Candidates.Name,
    Profiles.Profile_ID, Profiles.Profile
    FROM Profiles INNER JOIN (Candidates INNER JOIN
    CandidateProfiles ON Candidates.Candidate_ID =
    CandidateProfiles.Candidate_ID) ON Profiles.Profile_ID =
    CandidateProfiles.ProfileID;
    1, Iain, 1, Map making
    1, Iain, 2, Web design
    1, Iain, 7, Sport
    1, Iain, 8, Travel
    2, Fi, 3, Gardening
    2, Fi, 4, Hand therapy
    2, Fi, 8, Travel
    3, Rob, 5, Recruitment
    3, Rob, 6, Aviation
    3, Rob, 7, Sport
    and
    Vacancies_Query
    SELECT Vacancies.Vacancy_ID, Vacancies.Vacancy,
    Profiles.Profile_ID, Profiles.Profile
    FROM Profiles INNER JOIN (Vacancies INNER JOIN
    VacancyProfiles ON Vacancies.Vacancy_ID =
    VacancyProfiles.VacancyID) ON Profiles.Profile_ID =
    VacancyProfiles.ProfileID;
    1, Cartographer, 1, Map making
    1, Cartographer, Web design
    2, Gardener, 3, Gardening
    3, Occupational therapist, 4, Hand therapy
    4, Web designer, 2, Web design
    5, Recruitment manager, 5, Recruitment
    5, Recruitment manager, 6, Aviation
    So from these, I have a Candidates page that is based on the
    Candidates table listing just ID, name and tel in a repeat region,
    with a link to a details page based on the CandidatesProfiles query
    above, and likewise with the Vacancies.
    I'm just wondering how this works with editing and adding
    records - as on those pages, I want to be able to add /edit fields
    from the Candidates and Vacancies tables, but also add/edit the
    profiles for each - do i just need my Add/Edit pages to be based on
    the same CandidatesProfiles and VacanciesProfiles query / SQL
    above?
    I get how the page retrieving the data can display the
    existing records, including multiple profiles for each in a repeat
    region - but am less sure about adding / editing multiple profiles?
    Or would it be a two step process - ie have a page to add a
    Candidate, and then have a page that displayed the Candidate's
    details with a subform where you could add/attach profiles to each
    Candidate?
    Hope that makes some sense, and someone can point me in the
    right direction.
    Cheers,
    Iain

    Thinking about it, would it be possible to have a list of
    checkboxes on the insert/edit page, with each asigned a Profile -
    so for example :
    if checkbox1 is checked, add Candidate1, Profile1
    if checkbox2 is checked, add Candidate2, Profile2
    etc?
    Iain

  • Single form.. Insert records into multiple tables

    I have an unbound form that kicks off a process and I want to store the results of this process in the database. I can code this the old fashioned way with native jdbc calls, but was wondering if someone had a method for doing this with ADF BC.
    For example, the process will need to create:
    1 master record in table_a
    2 or more records in table_b
    2 or more records in table_c
    Thanks,
    Eric

    Hi,
    in ADF BC you would create a method e.g. on the AM level and then expose it as a client method to ADF. You can then - from within the method - access VO that are representing a table to create new records in them or - the old way - get access to the connection from the ApplicationModule and issue a prepared statement. It depends on the usecase and whether or not there exist a VO for the table to put in the data
    Frank

  • Inserting records into a table with all caps

    Hello
    I have a procedure that inserts records into a table. How do I ensure that the text values inserted are recorded all capital letters into the table?
    Thanks.

    You can use UPPER(..) function in your insert statement, so that values are converted to UPPER, before insert.
    If you want to check at table level, you can achieve that by writting a before insert trigger and in that trigger check
    IF UPPER(:new.<col>) != :new.<col> THEN
    RAISE_APPLICATION_ERROR(-20101,'Error: Not all values are in upper case')
    END IF;

  • Using Crystal 2008 to insert records into a table

    Hi,
    We have a unique need to use Crystal to insert records into a table. We have managed to test a report that can write into a temporary table.  This is done by using sql command object  and uses  the following code :
    INSERT INTO TEMP_TABLE  (ORDERID)
    VALUES ({?orderid})   (-- where orderid a parameter).
    This test report asks for an order id and then inserts the record perfectly fine.
    Now moving on to the real report - This report basically prints orders in batches and we want to insert order id into a temporary table to ensure we don't print orders that were already printed. To do this we created a sub report "insert orders" that has the above insert command. The main report passes the orderid to subreport and the idea is that the subreport would insert each time an order is passed. So if main report printed 50 orders ids, the then it would do 50 inserts individually into the temp table. 
    This however is NOT working. The report runs fine but there is no insert.  Our hunch is that  Crystal is not committing after every order id is passed from the main report.  Not sure if we can set the AUTO COMMIT ON  as a default somewhere?
    Wondering if any one has attempted this or has any insights?
    Regards,
    Mohit.
    Environment is - Crystal 2008 and Oracle 11GR2, we are using Oracle drivers (and not odbc)

    Hmmm... I don't use Oracle but the syntax looks good...
    You've already tested it and I assume that you are using the same driver in the production report as you used in the test, so that shouldn't be an issue...
    how are you pulling the data? Is the final SELECT statement that pulls the report data in the same command as the INSERT script, or is the INSERT script in it's own command?
    The reason I ask... If you are trying to pass a multi-valued parameter to a command, it won't work. If you have the insert command as it's own command while the data is being pulled with linked tables or a separate command, it is possible that the report itself will execute as expected w/o passing a value to the insert script.
    If it's all in 1 command (as it should be), a bad parameter would fail in the final SELECT causing an error.
    Also... are rows null or empty string values being added to table when the report executes? This would be an indication that the command is being executed but isn't getting the parameter value.
    Jason

  • Insert data into multiple tables

    Hi all,
    I've a requirement where i need to insert data into multiple tables using PL/SQL procedure
    Procedure should have two parameters
    1. Table Name (parameter1)
    2. Data (parameter2)
    Based on these two parameters i need to insert data into table (parameter1) using data (parameter2)
    ex:
    Procedure insert_data (p_table  IN VARCHAR2
                          ,p_data   IN -- what should be the datatype?
    IS
    l_statement VARCHAR2(2000);
    BEGIN
    -- insert data into tables
    INSERT INTO p_table
    values (....);
    END insert_data;Thanks in advance!!

    BEDE wrote:
    Amen to that!
    So, I believe a better approach would be the following...
    Suppose you have N datafiles with the same structure, and you wish to insert into the database the data from all those files.
    For that, you should have a single table, named, say incoming_file_data, which should be structured more or less like below:
    create table incoming_file_data (
    filename varchar2(250) not null -- name of the file inserted from
    ,file_time timestamp -- timestamp when the data was inserted
    ,... -- the columns of meaningful data contained in the lines of those files
    );And you will insert the data from all those files in this table, having normally one transaction for each file processed, for otherwise, when shit happens, some file may only get to be partially inserted into the table...
    Maybe one good approach would be to create dynamically an external table for the file to be loaded, and then execute dynamically insert select into the table I said, so that you will have only one insert select for one file instead of using utl_file... RTM on that.If the file structures are the same, and it's just the filename that's changing, I would have a single external table definition, and use the alter table ... location ... statement (through execute immediate) to change the filename(s) as appropriate before querying the data. Of course that's not scalable if there are multiple users intenting to use this, but generally when we talk about importing multiple files, it's a one-user/one-off/once-a-day type of scenario, so multi-user isn't a consideration.

  • Can BO Enterprize SDK inserts records into user table

    From Infostore can we create a jsp script using Java SDK to inserts records into user table??
    Thanks
    Amar

    Hi Amar,
    I want to retrieve data/records from Infostore and insert into a user table using JSP script. Is it possible to do this?
    Infostore is a database used by BO Server. so any changes made in infostore through BO enterprise session is valid.
    Say u want to retrive on of report present in folder <my folder>.
    The you have to query for that. for eg.
    boinfostore.query("select * from ci_infoobjects where si_kind ='report' and si_foldername='my folder'");
    Create/add/insert any new information in infostore is done by functionalities provide by SDK.
    like adding the user or scheduling a report will add new object to infostore.
    If you directly access cms database and make any changes then , I am afraid you will end up with nightmare.
    So it is always recommneded to access infostore/ cms database only from bo session.
    For more information refer below link
    [http://devlibrary.businessobjects.com/BusinessObjectsXIR2SP2/en/devsuite.htm]
    then under Contents
    BusinessObjects Enterprise SDK >>  COM developer guide and API reference >> Query Language Reference
    do revert if any queries
    Thanks,
    Praveen.

  • Inserting data into multiple tables in jdbc

    I am doing on file to jdbc. Now I got a requirement to insert data into multiple tables on the receiver side. How can I do this ?

    Hi,
    you are going to insert data into 4 tables in a sequence one after another , I see three options.
    1) Stored procedure and 2) creating 4 statement data structure (one for each table)
    The third option is writing a SQL with join for the 4 tables and use action command = SQL_DML. Example as follows....
    Write SQL code and place it in access tag. Pass values for the columns using key tag...
    <stmt>
        <Customers action="SQL_DML">
          <access> UPDATE Customers SET CompanyName=u2019$NAME$u2019, Address=u2019$ADDRESS$' WHERE CustomerID='$KEYFIELD$u2019
          </access>
          <key>
            <NAME>name</NAME>
            <ADDRESS>add </ADDRESS>
            <KEYFIELD>1</KEYFIELD>
          </key>
        </Customers>
      </stmt>
    Refer this http://help.sap.com/saphelp_nwpi71/helpdata/en/44/7b7855fde93673e10000000a114a6b/content.htm
    Hope this helps ....

  • Inserting records across multiple tables

    I'm still pretty new to working with databases, but have been
    fine using DW to use forms to add, edit and delete records from a
    flat table.
    I'm less sure about updating records across multiple tables,
    for example in a one to many rleationship with a look up table, eg
    If I have three tables
    Companies :
    CompanyID (INT, auto increment)
    Company
    Address
    etc
    Contacts :
    ContactID (INT, auto increment)
    FirstName
    LastName
    etc
    CompanyContacts :
    CompanyID (INT)
    ContactID (INT)
    It's straightforward enough to create pages to insert new
    records into the Companies or Contacts tables, but how do I go
    about populating the CompanyContacts table when I add a new record
    in the Contacts table, so that it becomes 'attached' to a
    particular 'Company'?
    If that makes sense.
    Iain

    I'm still pretty new to working with databases, but have been
    fine using DW to use forms to add, edit and delete records from a
    flat table.
    I'm less sure about updating records across multiple tables,
    for example in a one to many rleationship with a look up table, eg
    If I have three tables
    Companies :
    CompanyID (INT, auto increment)
    Company
    Address
    etc
    Contacts :
    ContactID (INT, auto increment)
    FirstName
    LastName
    etc
    CompanyContacts :
    CompanyID (INT)
    ContactID (INT)
    It's straightforward enough to create pages to insert new
    records into the Companies or Contacts tables, but how do I go
    about populating the CompanyContacts table when I add a new record
    in the Contacts table, so that it becomes 'attached' to a
    particular 'Company'?
    If that makes sense.
    Iain

  • How to insert records into the Table?

    Dear Sir,
    I'm new to JDeveloper. Now I managed to create a Frame in JDeveloper with many Text fields and a button. In the back end, I have a procedure to insert records to a table, to which I pass the values of the fields as parameters. Now I'm not getting the steps to call the PL/SQL Stored procedure when I click on the button. I'm using Oracle 9i JDeveloper version 9.0.3.1. and Oracle 9i Database.
    Please give me the complete steps to achieve my task - it is quite urgent.
    Thanking You in advance.
    Regards,
    Senthil .A. Perumal.

    The JDBC tutorial will show you how to call a stored procedure from Java:
    http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/basic.htm
    One more thing, why are you using such an old version of JDeveloper? any reason not to upgrade to the 10.1.3 version of JDeveloper?
    Also you might want to look into ADF and how it makes these type of database interactions easier.
    See this demo:
    http://www.oracle.com/technology/obe/obe1013jdev/adf_swing/master_detail_page_adfswing_bc.htm

  • Insert Records into another tables

    Hi guyz,
    I have four tables as below
    1) employee
    empid (primary key)
    deptid
    emp_name
    work_location
    date_of_join
    emp_status
    date
    2) Termination
    empid reference employee
    deptid
    emp_name
    work_location
    terminate_date
    3) Resignation
    empid reference employee
    deptid
    emp_name
    work_location
    resign_date
    4) Vacation
    empid reference employee
    deptid
    emp_name
    work_location
    vac_date
    i have list item on employee form --> emp_status is list item whic contain Termination, Resignation, Vacation
    i want to update employee as well other tables if user select the respected field from the list item.
    if the user select termination/resignation from the list item the date item will be enable and user should enter the date,otherwise give the error on commit please enter the date and when user commit the record on employee it should update the table employee and delete the record belongs to Termination/Reisgnation and the record will be insert into Termination/Resignation table as select by user from list item.i tried this before but im fail i write the below code on pre-update trigger as below
    begin
    insert into termination
    (empid,deptid,emp_name,work_location,termination_date)select (empid,deptid,emp_name,work_location,date from employee where emp_status='Termination';
    delete from employee where emp_status='Termination' ;
    end;
    same as on resignation
    anybuddy help me how to do this task? to update the tables. im new in oracle.
    Regards
    Edited by: user10648713 on Dec 21, 2008 4:29 AM

    You run into the classic Mutating table problem. You cannot issue DML-statement against the same table the trigger is based on in a FOR EACH ROW-trigger.
    But even worse, you will cause any kind of client program to get in trouble if you implement such a logic. The client issues an update and as a result the record gets deleted. And, for you have a forms-module based i tell you that you will get problems with your forms-module.
    I still can't see whats the sense behind it, putting records into different tables dependant on a status. Oracle is built to manage large data volumes, so even for a large number of records that doesn't make sense to me.
    But anyway if you still want to deal with that multi-table-approach, go for the following:
    You will need three triggers on your table: a before-statement, an after-statement and a for-each-row-trigger:
    The before-statement will initialize a list of PK-Items
    The for-each-row will add the id of the processed row to the list
    The after-statement will loop over the list and process the rows.
    Create a Package for handling the logic including three procedures
    CREATE OR REPLACE PACKAGE PK_TRIGGER IS
      PROCEDURE PR_BS;
      PROCEDURE PR_ARIU(i_nEmpId IN NUMBER);
      PROCEDURE PR_AS;
    END;
    CREATE OR REPLACE PACKAGE BODY IS
      TYPE tData IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
      lData tData;
      PROCEDURE PR_BS IS
      BEGIN
        lData.DELETE;
      END;
      PROCEDURE PR_ARIU(i_nEmpId IN NUMBER) IS
        iPos PLS_INTEGER:=lData.COUNT+1;
      BEGIN
        lData(iPos):=i_nEmpId;
      END;
      PROCEDURE PR_AS IS
        CURSOR crEmp(i_nEmpId IN NUMBER) IS
          SELECT *
            FROM EMP
           WHERE EMP_ID=i_nEmpId;
        recEmp crEmp%ROWTYPE;
        iPos PLS_INTEGER;
      BEGIN
        iPos:=lData.FIRST;
        LOOP
          EXIT WHEN iPos IS NULL;
          -- Do whatever you want with the data in the record
          OPEN crEmp(lData(iPos));
          FETCH crEmp INTO recEmp;
          IF crEmp%FOUND THEN
            IF :NEW.EMP_STATUS='Termination' THEN
              DELETE FROM emp
               WHERE EMPID=lData(iPos);
              INSERT INTO TERMINATION (
                empid,
                deptid,
                emp_name,
                work_location,
                t_date
              ) VALUES (
                recEmp.empid,
                recEmp.deptid,
                recEmp.emp_name,
                recEmp.work_location,
                sysdate
            END IF;
          END IF; 
          CLOSE crEmp;
          -- Process next record
          iPos:=lIds.NEXT(iPos);
        END LOOP;
        lIds.DELETE;
      END;
    END;Now create the three triggers calling the appropiate procedures.

  • Insert records into A table in Oracle from SAP

    Hello All,
    I want to know how can we insert a record into a table which is in another server say Oracle and this needs to be done everyday.
    For example, I have a record which gives the information whether the Daily Job has run Successfully or not. Now , I have to update this information in the Oracle table.

    refer amit perfect answer.
    Re: Need to put data in oracle table from sap.

  • Problem - Inserting Records into Hashed Tables

    Help for an ABAP Newbie...
    How do I insert records into a hashed table?
    I am trying the following, but get the error message,
    *You cannot use explicit or implicit index operations with types "HASHED TABLE" or "ANY TABLE".  "LT_UNIQUE_NAME_KEYS" has the type "HASHED TABLE".
    TYPES: BEGIN OF idline,
        id TYPE i,
        END OF idline.
      DATA: lt_unique_name_keys TYPE HASHED TABLE OF idline WITH UNIQUE KEY id,
            ls_unique_name_key LIKE LINE OF lt_unique_name_keys.
    " Create a record and attempt to insert it into the internal table.
    " Why does this cause a compilation error message?
    ls_unique_name_key-id = 1.
      INSERT ls_unique_name_key INTO lt_unique_name_keys.
    Thanks,
    Walter

    INSERT ls_unique_name_key INTO TABLE lt_unique_name_keys.

  • How do you insert new records into multiple tables using the same unique primary key?

    I’ve created a PHP site and MySQL server using a free app called XAMPP.  I have successfully created a form in Dreamweaver that will write data to a (name) table in the SQL database.  Here’s my question: How do you write to two (or more) tables in the same database and pass the same primary key to both tables?  In the SQL database, I defined the first field as ID and set it as the primary key with auto update.  So, when you insert a new record, it creates a unique primary key for that record.  In my form, I’m capturing info that needs to be stored to two tables at the same time; a Name table and Address table. Since the Name and Address tables use the ID field as the primary key, I believe I will need to pass the ID value from the Name table to the insert of the Address table to insure they both have the same primary key, right?

    No. You probably need the primary key from one table to be a foreign key in the other tables. In any case, I believe you can use two methods to obtain the auto generated key. First with SQL:
    http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
    And the other using a PHP function:
    http://us3.php.net/mysql_insert_id

  • How to delete the Table Contents before inserting records into SQL table ?

    Hello Experts,
            I have a scenario where in I have to Pick up some records from SAP RFC & insert into SQL table.
            i know how to do this scenario but the proble with this is before inserting we first have to ZAP the SQL table & insert a new records. One more twist is The Triggering is happening from SAP side with Sender RFC. If this would have been from SQL Side i could have written a Stored Procedure/ Trigger & could have called this before the SENDER JDBC communciation channel picks up the Triggering event from SQL side.
    So how to do this scenarioin XI, First deleting all the Records of SQL table & then inserting the new reocrds. without using the BPM.
    Regards,
    Umesh

    hi umesh,
    you can achieve this by writing SQL query in message mapping level..
    refer this link:
    http://help.sap.com/saphelp_nw04/helpdata/en/b0/676b3c255b1475e10000000a114084/frameset.htm
    regards.

Maybe you are looking for

  • Help with my 1st Ipod

    I just bought a new 3rd gen Ipod Shuffle 2GB. Opened it when I got home, but now I dont know what to do. I plugged it into my computer, and it said it detected a device and downloaded the drivers. Unfortunately that is all I can get it to do. Waited

  • Where can i find iweb

    We have been using iWeb for our family business for site development and maintenance. Lately, we bought new iMacs for our offices and we suddenly realized we cannot buy iWeb from apple anymore. It is nowhere to be found!!! Our site is useless now!!!

  • Automatic creation of employee vendor (KS01)

    I want to set up a process when HR sets up an employee, there could be an automatic set up of the corresponding vendor rather than a manual process as at present.. is there any SAP standard functionality to do this? any recommendations for the best w

  • Spry Collapsable Panel Question

    I just started using Spry and was wondering if there is an way to have a plus sign display next the the title when the panel is contracted but then when somebody clicks to open the content area it would change to a minus symbol? Thanks for your help

  • My x3 phone can't open any image file

    i updated my phone yestrday and after that, my phone cannot open any image files....it says 'no image to display'......now whats wrong with my phone????