Thursday, 12 February 2015

How to update data through RFC using JCo in SAP?

Before updating the data in SAP, we need to have a working connection to SAP.

Please refer my previous blog posts for connecting to SAP & retrieving data from SAP so that you get an overview of SAP connection basics and function templates for the CRUD operations.

Follow the first 4 steps as specified in the post retrieving data from SAP i.e., from imports till getting client object JCO.Client client = JCO.getClient(SID);

Next step is to set the criteria of the fields wrt the table for which we are updating the data. Note that Field is a class which need to be imported i.e.,      
 import com.sap.mw.jco.JCO.Field;
    .................
    .................
Field fieldname1 = jcoFunction.getImportParameterList().getField("FIELD_NAME_XXX");
fieldname1 .setValue("123");

If  you have more than one field criteria, you need to repeat the above two lines for as many fields as you want to set.
Note that FIELD_NAME_XXX is your actual field name specification & instead of 123, you need to set your own criteria.

Once the fields are set, just set all the column values for the required table with appropriate data i.e.,
JCO.Table YOUR_TABLE_NAME = function.getTableParameterList().getTable("TABLE_NAME_XXX");
YOUR_TABLE_NAME.appendRow();
YOUR_TABLE_NAME.setValue("111", "FIELD_NAME_XXX");
YOUR_TABLE_NAME.setValue("222", "FIELD_NAME_1");

YOUR_TABLE_NAME.setValue("333", "FIELD_NAME_2");
    .................
    .................

Then execute the function using the client object
  client.execute(function);

Executing function doesn't mean that your new data is updated to the row, it's only set. Now, you need to commit the data as we do in our database transactions.

Inorder to commit, we need to first get the function template of commit function available in SAP repository i.e.,
IFunctionTemplate commitfunctemplate = repository.getFunctionTemplate("BAPI_TRANSACTION_COMMIT");

Declare a function variable, say JCO.Function commitVar;

Using this variable commitVar, create your function template i.e., 
commitVar = new JCO.Function(commitfunctemplate);

Finally execute the commit function after a clean null check i.e.,
if (commitVar == null)
throw new Exception();
client.execute(jcoCommit);

That's it, your data is updated to SAP. 
Incase you want to check the return structure you can do this by using
JCO.Structure returnStruct = function.getExportParameterList().getStructure("RETURN");


As stated in my previous post, do not forget to release the client object & remove the connection pool. Needless to mention, handle exceptions wherever applicable & required.

Enjoy with your data updates :)

Thank you.












No comments:

Post a Comment