JDBC  Insert - Interesting!!

In JDBC 2.0 we can insert/update using programming language Java.
For an insertion, we do (assuming table name:COFFEES)
---other code here-----
ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");
uprs.moveToInsertRow();
uprs.updateString("COF_NAME", "Kona");
uprs.insertRow();
why do we have to call a moveToInsertRow()? Anyways the row is going to get inserted somewhere in the table and resultset. what difference does it make?

can some one find the dug for me ????
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Insert_data_Jdbc
     public static void main(String args[])
          Connection connection = null;
Statement stmt = null;
//ResultSet rs = null;
          System.out.println("I am in main");
          try
     // Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName).newInstance();
// Create a connection to the database
String serverName = "127.0.0.1";
String portNumber = "1521";
String sid = "oraval";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "scott";
String password = "tiger";
connection = DriverManager.getConnection(url, username, password);
//stmt = connection.createStatement();
//int i = 20;
String t= "INSERT into test values (?,?)";
PreparedStatement ps = connection.prepareStatement(t);
for (int n = 0; n < 10; n++)
ps.setInt(n,n);
          catch (ClassNotFoundException e)
// Could not find the database driver
     e.printStackTrace();
catch (SQLException e) {
     // Could not connect to the database
     e.printStackTrace();
catch (Exception e) {
e.printStackTrace();
finally
     //release resources
     /* if(rs!=null){
try {
// rs.close();
} catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
if(stmt!=null){
try {
stmt.close();
catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
     //      TODO Auto-generated catch block
     e.printStackTrace();
ta
sunny

Similar Messages

  • RFC to JDBC(Insert) async scenario

    Hi Experts,
    In RFC to JDBC(Insert) async scenario  we are getting the the response from JDBC as <insert_count>1</insert_count> after inserting in to DB . Is there any way to stop getting response?
    Regards,
    Raj

    <insert_count>1</insert_count>
    Firstly this is not an error but an acknowledgement from the JDBC that the Insert for the corresponding Statement node is successful. The count 1 represents that you have made just one Insert-Statement call to the JDBC......had there been no Insert in the DB then you could have got 0 insetad of 1.
    Normally happens when the sender requests for an acknowledgement. Don have knowledge on the ABAP-front so cant comment on the blog given by Prateek, but seems that because of the sync nature of RFC you are getting this ack from JDBC...
    Regards,
    Abhishek.

  • JDBC Insertion Response

    Hello everybody,
    I have the next scenario:
    R/3 IDOC -> XI -> Oracle JDBC Insertion
    the problem is that the database is returning the reponse of the insertion and the idocs are asynchronous, so XI gives an error of mapping cause I can't map a synchronous interface to a asynchrounous one, can anyone help me with this problem any suggestions?????
    Thanks in advance,
    Regards,
    Julio Cesar

    Hi,
    If you want pass the data from IDOC to Oracle database to update the information of Oracle table,it is possible.
    see this for sample weblog....
    /people/prateek.shah/blog/2005/06/08/introduction-to-idoc-xi-file-scenario-and-complete-walk-through-for-starters
    For target JDBC structure see the following weblog...
    /people/sap.user72/blog/2005/06/01/file-to-jdbc-adapter-using-sap-xi-30
    and also refer
    Re: IDOC to File Scenario
    Thanks
    Vikranth

  • JDBC insert with XMLTYPE data type

    Hi,
    SOAP to JDBC scenario. Oracle 11G as a receiver.
    Requirement is to  insert whole xml payload message in one of Oracle table fields as a xml string. Target oracle DB table column is defined with XMLTYPE data type, it has capacity to hold xml data more than 4GB. I am using graphical mapping with direct INSERT statement.
    When I try to insert xml payload with smaller size transaction goes through. However when the xml payload size increases it is giving following error in JDBC receiver communication channel monitoring.
    Could not execute statement for table/stored proc. "TABLE_NAME" (structure "StructName") due to java.sql.SQLException: ORA-01704: string literal too long
    Here is insert statement as in communication channel monitoring. (Note: XML payload with bold characters is truncated)
    INSERT INTO  TABLE_NAME (REQ_ID, OUTAGE_OBJ, TIMESTAMP, PROCESSED_FLAG) VALUES (VAL1, <?xml version="1.0" encoding="UTF-8"?>............</>, TO_DATE(2010-11-15 10:21:52,YYYY-MM-DD HH24:MI:SS), N)
    Any suggestions to handle this requirement?
    Thank you in advance.
    Anand More.

    Hi Anand,
    The problem here is definitely the length of the SQL query. i.e "INSERT INTO ......... VALUES......."
    This is what i got when i searched for this ORACLE error code:
    ORA-01704: string literal too long
    Cause: The string literal is longer than 4000 characters.
    Action: Use a string literal of at most 4000 characters. Longer values may only be entered using bind variables.
    Please ask a ORACLE DB expert on how to handle this Also i am not sure how can we handle Bind Varibales in SAP PI.
    I hope this helps.
    Regards, Gaurav.

  • PI JDBC INSERT Failed but message is registered as successful

    Dear all,
    We have a scenario where we send an IDOC with prices of several materials to PI and then using JDBC we send it to an SQL database. During the mapping, we create an INSERT statement for each segment of the IDOC .
    The problem is, that sometimes one or more insert statements may fail (the customer can see no new lines in the database), but in the monitoring everything seems ok . The message has a "processed successfully"  status so there is no way for the customer to know that something went wrong so each time they check the prices one by one .
    The strange part is that if they find a mistake, they just resend the same message and after one or two tries it works ! This indicates that the problem is not in the actual data but somewhere else (probably in the database ?) .
    So, one problem is why the data is not written and the second issue is why the message is logged as successful although one query has failed ,
    Thank you all for your help .

    Thank you for both for your quick response .
    Unfortunately this scenario is up and running for quite some time already and the customer does not want to change it . Also, I am not sure how I could make an Insert statement that would include many lines .
    Right now, the mapping produces the following result (I only post the first two statements, the actual number is around 500)
    <Statement><dbTableName action="INSERT">
    <table>min_sapsrs_price</table>
    <access><STAT>0</STAT><
    ACT_DATE>20100701</ACT_DATE>
    <MOD_DEL>MOD</MOD_DEL>
    <INTCODE>000000000014009003</INTCODE>
    </access>
    </dbTableName>
    </Statement>
    <Statement>
    <dbTableName action="INSERT">
    <table>min_sapsrs_price</table>
    <access><STAT>0</STAT>
    <ACT_DATE>20100701</ACT_DATE>
    <MOD_DEL>MOD</MOD_DEL>
    <INTCODE>000000000014009004</INTCODE>
    </access>
    </dbTableName>
    </Statement>
    could you please tell me how should I propose them to do it ?

  • Mapping multi-segment IDOC to multiple JDBC INSERT statements

    Hi Everyone,
    This is probably going to be easy for the experienced PI developers out there but I'm just starting out in this technology. We are running PI 1.11 and the scenario is as follows. We have a bespoke IDOC message type ZSTOCK which can contain 1-many segments with the following field content:
    WERKS
    MATNR
    VBELN
    ACT_LABST
    AVL_LABST
    For each segment in the source IDOC, I want to generate an INSERT statement to insert a row in an SQL table via the JDBC adapter with the following columns:
    Plant
    Material
    SalesOrd
    ActStock
    AvlStock
    Basically, each field on the source IDOC segment maps directly onto the target column of the SQL table. The problem is, on a multi-segment IDOC only the first segment is generating a row in the SQL table. I've seen a number of threads on this forum that seem to tackle the same issue but the solution is either missing or unclear. I think the solution lies somwhere in the occurrences of the STATEMENT node in my target message type and perhaps specific definitions in the message mapping. Can anyone help solve this mystery?
    Thanks,
    Gary

    Hi Gary
    If you created a data type, try to change occurrence of STATEMENT node to 0..unbounded or 1..unbounded.
    In the message mapping, map the target STATEMENT node with the source 1-many segment.
    You can find [here|http://help.sap.com/saphelp_nw70/helpdata/en/4d/8c103e05df2e4b95cbcc68fed61705/content.htm] more informations about the JDBC structure
    Regards,
    Giuseppe

  • JDBC insert empty STRUCT (JGeometry) into SDO_GEOMETRY

    Hi!
    I need to insert empty or null value intro oracle table with SDO_GEOMETRY field.
    I'm using prepared statement.
    I have tried pstmt.setNull(1, null), pstmt.setObject(1, null)
    Normaly I do it like this:
    STRUCT obj = JGeometry.store(jgeom, conn);
    pstmt.setObject(1, obj);
    So I probably need to create an empty STRUCT or something.
    I have also tried using :
    StructDescriptor type_descriptor = StructDescriptor.createDescriptor ("MDSYS.SDO_GEOMETRY", conn); but I don't know if I'm using it right.
    The syntax is like:
    StructDescriptor structdesc = StructDescriptor.createDescriptor (sql_type_name, connection); but I don't know what sql_type_name means? Is it tablename, fieldname? Tried them all...no success.
    I've read that JDBC doesn't support that kind of insert with setNull, is there a workaround or any other way of doing this.
    Thanks in advance and have a nice day.
    Simon

    http://www.oracle.com/technology/tech/java/sqlj_jdbc/pdf/a96654.pdf seems to have the clues that you are looking for.
    BTW, we are adding a Connection.createStruct/Array method so that you can create these types of objects in portable with JDBC in JDBC 4

  • JDBC Insert takes more time

    Hi,
    We are using BPM to insert a JDBC table.  The send step takes 5 mins to insert 10k records.  We have used similar design in other processes but does not take much time,.
    What would be the issue?  
    Regards
    Krish

    Krish,
    We are using BPM to insert a JDBC table.  The send step takes 5 mins to insert 10k records.
    I think that indexing has not been done. Verify that. if not, do the indexing which will reduce the processing time significantly.
    Regards,
    Neetesh

  • JDBC Insert

    hi folks,
    I have a oracle table with USER_ID as primary key.
    Using JDBC i m trying to insert a row with same USER_ID and hence violating primary key rule.
    try {
    stat.executeUpdate(SQL);
    catch(SQLException ex)
    Now JDBC throws me a sql Exception, with scary message "ORXXX ....."
    Is any other way to detect that i m violating primary key rule ?
    How abt firing a SQL query before i insert the new row into database.
    eg. select count(1) from table where USER_ID='X'.
    If count == 1, then i know that record already exits.
    But the downside is that, 2 SQL queries for a insertion. ?
    Ur thoughts will be greatly appreciated.

    As duffymo states a unique constraint is absolutely the right thing to do to ensure no two usernames are the same.
    To go back to an earlier point, once you have this unique constraint in place, if you want to avoid getting the unique constraint error if someone attempts to insert a username that already exists, or you want to be able to handle it you could:
    1) As you've already considered, you can test for the presence of the username prior to inserting. Results in additional round trip and there is of course a small period of time between testing for it and actually inserting that someone else might consume that username.
    2) You can get at the vendor-specific error code that caused a SQLException with SQLException.getErrorCode() and test for it. This has all the usual cavets that you'll be limiting your code to work on Oracle if you use this technique. Of course, this might not be an issue for your application and there are ways to isolate database-specific dependencies anyway.
    T

  • Jdbc insert fails with 01722: invalid number but sqlplus doesn't

    I am experiencing a 01722: invalid number on a remote system in Canada. Initially, I couldn't insert '0.0' into a number field, but after changing the ...Oracle/HOME0 ... registry value from ENGLISH_CANADA.WE8MSWIN1252 to AMERICAN_AMERICA.WE8MSWIN1252 and recycling the App Server (Oracle client) I was able to insert '0.0' into a number field.
    But my java app using JDBC had the same error "ORA-01722: invalid number" occurring for the same table and attribute -- only this time -- when I attempted to manually insert the same insert '0.0' into a number field -- it worked via SQLPlus.
    The NLS_Lang is set to AMERICAN_AMERICA.WE8MSWIN1252.
    I confirmed that the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\ACP value is 1252.
    Assuming a theory that maybe it is a setting on the DB Server, I tried reproducing this problem locally in my lab configuration by setting the NLS_Lang registry value to ENGLISH_CANADA.WE8MSWIN1252. I used the same jdbc test app to issue the insert....but it worked.
    --- Any advice on what other configuration changes could influence the number data type or whether it is possibly a DB Server setting instead of client -- would be greatly appreciated.

    JDBC does not care about NLS_LANG. It takes the Java default locale, maps it to Oracle language/territory pair and sends to the server.
    Just try this:
    Statement stmt = conn.createStatement();
    stmt.execute( "ALTER SESSION SET NLS_NUMERIC_CHARACTERS='.,'" );
    or bind numeric datatypes.
    -- Sergiusz

  • Unreliable JDBC Inserts & Updates

    I have a java web application (struts-based) on my machine that accesses a remote mysql instance. 50% of the time, when I execute an INSERT, I get a java.net.Connection error.
    More facts:
    [1] Servlet accepts parameters via html page to create dynamic sql statements,
    [2] If I navigate from the INSERT error message BACK once to the populated form and hit submit again, it successfully updates 95%(?) of the time,
    [3a] About 20% of the time, I get a connection error with UPDATE transactions,
    [3b] As in [2] above, if I go BACK, and submit again, it successfully updates 95%(?) of the time,
    [4] DELETE transactions almost always work,
    [5] I have noticed unreliable execution before in other JDBC based programs when accessing this mysql instance,
    [6] UPDATEs, and INSERTs properly update about 95% of the time when executed from my JEdit client plug-in. This plug-in uses JDBC to connect.
    A. Are you aware of any mysql configuration adjustments that can be made to make this process more reliable?
    B. Can you explain this toggling behavior: Never works 1st time, almost always works the 2nd time?
    thanks for your time,
    douglas reames

    where exactly is this exception coming from? the driver or some intermediate layer?
    is the mysql server maybe too busy or maybe needs to have it's number of max connections increased?
    a few thoughts but it will be more helpful to isolate what exactly is causing the error.

  • Problem executing a JDBC Insert on PI 7.1

    Hi,
    I'm trying to do a simple insert to a database in 7.1. but it keeps failing.
    The database table has been defined to allow nulls in every field.
    The mapping has been tested and maps correctly resulting in the following XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <StatementName1>
         <dbTableName action="insert">
              <table>customer</table>
              <access>
                   <forename>Smith</forename>
                   <surname>John</surname>
                   <address1>1 streets ville</address1>
                   <address2>park avenue</address2>
                   <address_town>MyTown</address_town>
                   <address_county>Any County</address_county>
              </access>
         </dbTableName>
    </StatementName1>
    </root>
    The error is:
    com.sap.engine.interfaces.messaging.api.exception.MessagingException: Error processing request in sax parser: Error when executing statement for table/stored proc. 'null' (structure 'Surname'): java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    I have checked the logs on the database side and no statement has been logged.
    I have logSQLStatement as true on the communication channel. Again no statement logged.
    Any help much appreciated.
    Kind regards,
    John

    Hi John Lambert,
    I understand, when you logon to database, you are able successfully execute
    insert into customer (FORENAME,SURNAME) values ('john', 'smith');
    Now let's debug why XML structure is not working.
    Step 1:- In Interface Determination, do not refer to Operational Mapping (delete only OM from there, not the Receiver Message Interface). By doing so, you are not call the OM (which refer to Graphical Mapping (MM refer to Data Type (which may be wrong)). Note: As there is no OM, we need to send the exact payload (XML) required by receiver JDBC from Runtime Work Bench, for testing purpose.
    Step 2:- So now, you have to construct equalant XML structure to String "insert into customer (FORENAME,SURNAME) values ('john', 'smith');".
    SAP Help [Link1|http://help.sap.com/saphelp_nwpi711/helpdata/en/44/7b67fffde93673e10000000a114a6b/frameset.htm]
    <StatementName>
      <dbTableName action=u201DINSERTu201D>
        <table>customer</table>
          <access>
             <FORENAME>john</FORENAME>
             <SURNAME>smith</SURNAME>
           </access>
    </StatementName>
    Step 3:- Now use the XML you have constructed, to test the scenario from RWB. If it is successful.
    Step 4:- Now design your Message Mapping in such way that it will give output as above XML.
    Step 4:- Invert the changes done in Step 1. Include OM in Interface Determination.
    Regards,
    Raghu_Vamsee

  • JDBC insert statement problem

    i have the following code. please help me out.
    import java.io.*;
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.ResultSet;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement ;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BookIssue extends JFrame
         JComboBox cbBooks;
         JLabel lblIssue;
         String selectedBook;
         JButton btnIssue;
         public BookIssue(String title)
              super(title);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               lblIssue = new JLabel("Select books from combo box",JLabel.CENTER);
               btnIssue = new JButton("Issue");
              cbBooks = new JComboBox(new Object[] {"RaghuRamkrishnan","J2CR","Netwrok Security"});   
              Container cp=getContentPane();
              setLayout(new FlowLayout());
              cp.add(lblIssue);
              cp.add(cbBooks);
              cp.add(btnIssue);
              selectedBook =(String) (cbBooks.getSelectedItem());
              btnIssue.addActionListener(new IssueListerner());
              setSize(300,300);
              setVisible(true);
         }// constructor end
         class IssueListerner implements ActionListener
              Connection conn;
              Statement stmt;
                   public void actionPerformed(ActionEvent ae)
                         try
                              if(btnIssue==ae.getSource())
                                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                  conn = DriverManager.getConnection("jdbc:odbc:JemNat","","");
                                  stmt=conn.createStatement();
                                  stmt.executeUpdate("Insert into StudentIssueDetails(BookName) values(selectedBook)");
                             }///End outer if
                             stmt.close();
                             conn.close();
                         } //end try
                         catch(SQLException exc)
                             exc.printStackTrace();
                        catch(Exception exc)
                             exc.printStackTrace();
                    }   /// end function
          public static void main(String[] args)
              new BookIssue("Book Issue");
    } ///end class
         getting the following list of errors::
    ---------- java ----------
    RaghuRamkrishnan
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6958)
         at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7115)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3111)
         at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
         at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:288)
         at BookIssue$IssueListerner.actionPerformed(BookIssue.java:59)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
         at java.awt.Component.processMouseEvent(Component.java:5488)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
         at java.awt.Component.processEvent(Component.java:5253)
         at java.awt.Container.processEvent(Container.java:1966)
         at java.awt.Component.dispatchEventImpl(Component.java:3955)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
         at java.awt.Container.dispatchEventImpl(Container.java:2010)
         at java.awt.Window.dispatchEventImpl(Window.java:1774)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

    stmt.executeUpdate("Insert into
    t into StudentIssueDetails(BookName)
    values(selectedBook)");What is this 'selectedBook'? Is this a variable name?
    In that case, you shouldn't be just writing it within the string. That would be an incorrect SQL. It should look like:
    stmt.executeUpdate("Insert into StudentUssueDetails(BookName) values('" +selectedBook +"')");Of course, a better way is to use PreparedStatement.

  • Does JDBC insert a value into the Primary Key?

    Hi,
    I'm using a servlet to input data froma n html form ,into an ACCESS Database.I'm using SQL statements i t he servlet ,and i'm confronted with the question:
    ALL database records are indexed with B_ID as the "Primary Key".
    I want to know: If I add the fields without a B_ID ..will SQL/JDBC/Access automatically add one for me?
    Or must I create the system that will count the records before adding a new B_ID?
    Hope you can help me.Thanks!
    Aesh83

    Access has a datatype claus for this autoincrement feature.
    I just can't remember its name.
    If you have such a primary key column in your table, you would simply insert values in each column except that, so this would automatically generate its value by incrementing the key.
    Your INSERT had to enumerate all columns you explicitely fill with values and skip this key column and those ones which shall be set to NULL btw. the defined default value (is there a DEFAULT clause in Access?)

  • JDBC insert single quote ???

    Hi,
    I want to insert a string which could contain a single quote ( ' ) into my database . But if this is the case, the regular insert command fails, since the single quote from the string collides with the ones from the command. What can I do???

    Try placing an escape char "\".
    So its like:
    String s="Sachin\'s page";
    If ur using it in xml use:
    &apos; to replace '.
    Hope this helps.
    Sachin

Maybe you are looking for

  • Hard disk installation and configuring?

    What is step by step procedure for installing 2nd hard disk into x86 box? What are the files to be edited? This was interview question by Sun .pls help.

  • Backspace

    Hi, is there a way to backspace automatically without the user having to press backspace. e.g. int selection = inputting.nextInt(); while ((selection < 1) || (selection > 2)) selection = inputting.nextInt(); In the above code the user is forced to se

  • SAP BOXI 3.1 - Error in stdout.log

    Hi all, in the stdout.log file the following error occurs intermittently: {ERROR} [/OpenDocument].[action] Thread [http-8080-Processor12];  Servlet.service() for servlet action threw exception java.lang.IllegalStateException at org.apache.catalina.co

  • User Exits for Purchase order & requistion to control Material description

    Dear Experts, I am creating a Purchasing requisition & Purchase order for certain Material Type. Currently user can change material description at item level without anu check. Now I have different material type like PACKING(ZPAC), Raw material(ZROH)

  • Pernr change type field

    Hi, Does anybody know if is possible to change type field PERN ?? We need this field were type char, not type numc. Thank you in advance, Marta.