Using exceuteBatch() while using PreparedStatement

Hi All,
I am using PreparedStatement and then further use addBatch() to
add queries and finally executeBatch()....
My problem is that if one of the queries added to the batch
fails it throws a SQLException and i have no means of finding
the position(i.e which query) threw the Exception...
But if i use Statement instead of PreparedStatement in the same
situation BatchUpdateException is thrown...whose method
getUpdateCounts() enables me to get the number of queries
already written and the position of the error....but this
results in considerable performance degradation....
So I have to use PreparedStatements and also want the
funtionality provided by BatchUpdateException...
Can anyone help me with this....
Its urgent...
Malhi

Hi Andy,
When we do pstmt.setString("SYSDATE"), behind the screen it goes as 'SYSDATE' (since its string) and will not be appended to the query as SYSDATE.
So append the SYSDATE to the query while preparing your statement.
String insertsql = "insert into emp (empid, name, dept , joindate) values (?, ?, ?, SYSDATE ) ";
PreparedStatement pstmt = conn.prepareStatement(inssql);
pstmt.setInt(1, 123);
pstmt.setString(2, "my name");
pstmt.setString(3, "my dept" );
pstmt.executeUpdate();
Regards
Elango.

Similar Messages

  • Update using preparedstatement

    Hi
    I am using preparedstatement to fire insert / update statements.
    the update query is taking a lot of time(min 150 ms) where as the insert query takes 0 ms .
    i'm using mssql driver with sql2000.
    what might be the problem???
    Regards
    Ravi

    in case of static the index costs only 38% where as in
    case of dynamic query the index costs 96%
    tht's the reason the dynamic query is taking more time
    also in case of static INDES SEEK is used where as in
    case of dynamic execution INDDEX SCAN is used so
    INDEX SEEK gets the record in one attempt where as
    indexscan scans the whole table to get the record so
    the row count in this case is same as the no of
    records in that table.
    now the question is how can i change the data access
    path /execution plan for the dynamic execution so that
    it should also look for index seek instead of index
    scan.Just to be clear, your Statement query is dynamic, while your PreparedStatement is static. In a previous post you implied that Statement was taking longer, but in this note you are implying that the PreparedStatement is taking longer. I'll let you work out which is which, but it appears that it is in fact a difference in the data access path that is causing the decreased performance.
    I am not a SQL Server expert by any means, but it is possible that someone else can provide you some specific suggestions on what to do next. I am curious why you want to use a Statement vs PreparedStatement (or vice versa). There have been multiple posts discussing the differences and in most cases from a programmers perspective PreparedStatements are superior because they automatically manage many of the data transformations for you (like escape characters for quotes). PreparedStatements are usally recommended by the DBA when a SQL is going to run repeatedly and frequntely to avoid having the database to re-parse the SQL all the time. Having said that, there are still many cases where using dynamc SQL makes sense and yours may be one of these (not sure).
    So, anybody with strong SQL Server have any suggestions for the OP?
    You may want to post this specific performance question out to a SQL Server forum too...

  • Using PreparedStatement.setString() on AS/400 VARGRAPHIC field not working

    Hello,
    I have a database table on an AS/400 that contains a VARGRAPHIC field of length 254. According to all the docs that I've read, I should be able to use PreparedStatement.setString() to set a parameter for that field. However, I never get any rows back when I execute the query. If I run the same query on the AS/400 using strsql, the query runs fine and returns the expected results. Anyone have any ideas?
    Thanks

    The Toolbox driver. In that case you might be better off asking this question in a forum that specializes in that. Go here:
    http://www-124.ibm.com/developerworks/oss/jt400/
    You will find a FAQ section, a mailing list you can subscribe to for discussions such as your question, a bug report page where you may be able to see if your question has already been reported as a bug, and so on.
    I haven't used VARGRAPHICS fields so I have no insight into your problem, except that setting graphics data from a String sounds kind of fishy to me. Good luck.

  • How to write SDO_GEOMETRY using PreparedStatements ?

    Hi there,
    I use JDBC and JDK 1.3+
    Currently I'm writing geometries into Spatial by using Strings and
    I meet some limitations for very huge geometries.
    That's why I need to use PreparedStatements and parameters to get
    rid of this limitation.
    My question is how can I write Object types by using JDBC. All
    the sample codes I found use oracle.sql and oracle.jdbc packages.
    My problem is that my code can be used by people that may not
    have an Oracle jdbc driver like "thin" for instance.
    thanks for your help,
    ALI

    Justin,
    I have a PL/SQL package that contains several functions. One of them does selection and filtering of spatial features based on a user's location and preferences. For this purpose a web-application runs this function.
    I would like this function to do the following:
    1. the function is called, user parameters are passed in
    2. a call to a java-stored-procedure is made. This java procedure creates a polygon based on the user's location and preferences.
    3. the polygon is returned to the PL/SQL function
    4. the funtion uses the returned polygon to query spatial features that intersect, etc.
    I can do the call to the java-stored-procedure but where I get stuck is how to get the polygon from java to pl/sql. I can return a String or a number from java but how can I return the polygon (e.g., STRUCT, java object)?
    The current solution uses a work-around by storing the polygon in a temporary table. I would like to change this because once the function has run, the polygon is not needed anymore so I would like to do without having to store the polygon.
    Markus

  • Queries with date functions using PreparedStatement for multiple DB

    I am developing application that uses DB independant queries. I am using preparedstatement to process the queries. I need to use date functions for query selection criteria.
    for eg.
    selecting the list of employees who had joined in the last 15 days
    selecting list of employees who had joined between two dates etc.
    where Date Joined field is a Timestamp value. To extract date no DB specific function can be used.
    If I use setMonth, setYear etc.. to set params in the pstmt the query becomes complex in the above case. Can any one throw some light on how to do the above in preparedstatement or any other better alternative.
    Tx a lot

    Hi,
    I did not mean that way. I presume that there is a timestamp value (may be a date too) column in the table. Then based upon your requirement (say before 15 days) pass the value as date (or time stamp) in the query as a parameter.
    String qry = "select * from myTable where join_date <= ?";
    stmt.setDate(1,myDate); // this is where you will have to manipulate the value to suit your DB timestamp or date value; you will have compatibility issues with util.Date and sql.Date so use Calendar class to satisfy.Feel free to mail me if you need further clarifications to [email protected]
    Cheers,
    Sekar

  • Using PreparedStatements

    Can anyone explain what does the following error mean? I'm getting it when I use PreparedStatements to connect in a MS Access 2000 database.
    Context log: path="" Error in jsp service() : [Microsoft][ODBC Microsoft Access Driver]Optional feature not implemented
    javax.servlet.ServletException: [Microsoft][ODBC Microsoft Access Driver]Optional feature not implemented
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:386)
         at src._0002fsrc_0002fuserDetails_0002ejspuserDetails_jsp_18._jspService(_0002fsrc_0002fuserDetails_0002ejspuserDetails_jsp_18.java:163)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:126)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.runtime.JspServlet$JspServletWrapper.service(JspServlet.java:174)
         at org.apache.jasper.runtime.JspServlet.serviceJspFile(JspServlet.java:261)
         at org.apache.jasper.runtime.JspServlet.service(JspServlet.java:369)
         at com.borland.jbuilder.webserverglue.tomcat.jsp.JspLoaderEcho.service(Unknown Source)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:503)
         at org.apache.tomcat.core.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:163)
         at ServletHandler.goToPage(ServletHandler.java:30)
         at ServletHandler.doPost(ServletHandler.java:21)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:503)
         at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:597)
         at org.apache.tomcat.servlets.InvokerServlet.service(InvokerServlet.java:257)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:503)
         at org.apache.tomcat.core.ContextManager.service(ContextManager.java:559)
         at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:160)
         at org.apache.tomcat.service.TcpConnectionThread.run(SimpleTcpEndpoint.java:338)
         at java.lang.Thread.run(Thread.java:484)

    There is no method called 'PreparedStatement'.
    PreparedStatements have nothing to do with MS Access, and accessing MS Access via ODBC does support PreparedStatements.
    Your code, or something that you are calling, is calling a method that the driver you are using does not support. This is most often associated with scrollable result sets and other stuff found in JDBC 2/3.

  • Database Procedure Calling by Using PreparedStatement and CallableStatement

    Hi
    We can execute Database Stored Procedure by using PreparedStatement and CallableStatement as well.Then what is the significance of having CallableStatement.
    Please let me know the difference between these two Statement objects particularly in Stored Procedures Execution.
    Thanks in advance
    Basha007

    A callable statement excecutes a stored procedure that's stored and run on the database server.
    A prepared statement doesn't require a database stored procedure. It's parsed and cached by the JDBC driver, and allows you to specify parameters and bind values to them at runtime. Those are usually used in loop constructs where you want to repeatedly execute the same SQL with different values.
    Not all RDBMS support stored procedures (e.g., MySQL), but every driver I've used allows PreparedStatements. - MOD

  • [svn:bz-trunk] 12162: Updated using PreparedStatements.

    Revision: 12162
    Revision: 12162
    Author:   [email protected]
    Date:     2009-11-24 08:17:44 -0800 (Tue, 24 Nov 2009)
    Log Message:
    Updated using PreparedStatements.
    CheckInTests: na
    Modified Paths:
        blazeds/trunk/apps/samples/WEB-INF/src/flex/samples/crm/company/CompanyDAO.java

  • [svn:bz-trunk] 12163: Update using PreparedStatements - bug blz-461

    Revision: 12163
    Revision: 12163
    Author:   [email protected]
    Date:     2009-11-24 08:19:56 -0800 (Tue, 24 Nov 2009)
    Log Message:
    Update using PreparedStatements - bug blz-461
    checkintests: na
    Ticket Links:
        http://bugs.adobe.com/jira/browse/blz-461
    Modified Paths:
        blazeds/trunk/apps/samples/WEB-INF/src/flex/samples/crm/employee/EmployeeDAO.java

  • Conditinal update using PreparedStatement

    Hi,
    I have situation where in I need to create dynamic sql statements based on user input.
    let's say user changes his last name or only first name or some comments field only those fileds changed should be updated in database leaving rest un changed.
    I am using PreparedStatement to update (this switched to over come single quote issue with oracle).
    if it was simple insert/update i could user statements but how can I do conditinal update using one prepared statement?
    any help

    From what I've read in the docs and experienced with Oracle drivers, it can't be done. The only way to dynamically create a prepared statement would be to create an update string conditionally based on the changed inputs, then create the PreparedStatement after the conditional checks(same technique you would use to dynamically create a Statement). But that doesn't really fit the criteria laid out by your initial post(only one PreparedStatement for all conditions).
    You could also use the CallableStatement and generate your update statement in the CallableStatement the same way you would generate the UPDATE dml using a Statement?
    Jamie

  • Use Preparedstatement to delete several rows from database

    Hello everyone,
    I am trying to delete multiple rows from database at one time using Preparedstatement.
    It works well when I tried in SQL directly,the sql query is as follows:
    delete from planners_offices where planner ='somename' and office in ( 'officeone', 'officetwo', 'officethree')
    I want to delete those 3 rows at one time.
    But when I am using preparedstatement to implement this function, it does not work. It did not throw any exception, but just does not work for me, the updated rows value always returns "0".
    Here is my simplified code:
    PreparedStatement ps = null;
    sqlStr = " delete from PLANNERS_OFFICES where planner = ? and office in (?) "
    Connection con = this.getConnection(dbname);
    try
    //set the sql statement into the preparedstatement
    ps = con.prepareStatement(sqlStr);
    ps.setString(1,"somename");
    ps.setString(2,"'officeone','officetwo','officethree'");
    int rowsUpdated =ps.executeUpdate();
    System.out.println(rowsUpdated);
    //catch exception
    catch (SQLException e)
    System.out.println("SQL Error: " + sqlStr);
    e.printStackTrace();
    catch (Exception e) {
    e.printStackTrace();
    } finally {
    this.releaseConnection(dbname, con);
    try{
    ps.close();
    }catch (SQLException e){
    e.printStackTrace();
    rowsUpdated always give me "0".
    I tried only delete one record at one time, "ps.setString(2, "officeone");", it works fine.
    I am guessing the second value I want to bind to the preparedstatement is not right, I tried several formats of that string, it does not work either.
    Can anyone give me a clue?
    Thanks in advance !
    Rachel

    the setString function in a preparedStatement doesn't just do a replace with the question mark. It is doing some internal mumbojumbo(technical term) to assign your variable to the ?.
    If you are looking to do your statement, then you will need to put in the correct of # of question marks as you need for the in clause.
    delete from PLANNERS_OFFICES WHERE PLANNER = ? and office in (?,?,?)
    If you need to allow for one or more parameters in your in clause, then you will need to build your SQL dynamically before creating your prepared statement.
    ArrayList listOfOfficesToDelete ;
    StringBuffer buffer = new StringBuffer("DELETE FROM PLANNERS_OFFICES WHERE PLANNER = ? AND OFFICE IN (");
    for(int i = 0; i < listOfOfficesToDelete.size(); i++ )
       if( i != 0 )
           buffer.append(",");
       buffer.append("?");
    buffer.append(")");
    cursor = conn.prepareStatement( buffer.toString() );
    cursor.setString(1, plannerObj);
    for(int i = 0; i < listOfOfficesToDelete().size(); i++ )
        cursor.setString(i+1, listOfOfficesToDelete.get(i) );
    cursor.executeUpdate() ;

  • Using PreparedStatement to execute a SQL Query

    hi All,
    I am trying to use PreparedStatement to execute a Query in Java.
    The Problem is that where Clause of that Query is dynamically formed as per
    user inputs .
    So , in this case will it help if I use PreparedStatement in place of Normal Statement ?
    If Yes , then how to handle the Dynamic where clause of the Query ?
    Thanks in Advance.
    Regards,
    ninad

    Let's say the user is providing a name, and you'r querying based on that name: PrepartedStatement ps = con.prepareStatement("select * from my_table where name = ?);
    ps.setString(1, nameFromUser);
    ResultSet rs = ps.executeQuery();
    http://java.sun.com/developer/onlineTraining/Database/JDBC20Intro/

  • How to insert the system date  using PreparedStatement

    How do I insert system date(from Orcale database) using
    PreparedStatement. I am aware that that oracle has date
    function 'sysdate' to retrieve the database current date.
    How Do i use that in the following syntax?
    Alertnative 1:
    String inssql =
    "insert into emp (empid, name, dept, updateDate) "+
    " values (?, ?, ?, ?)";
    PreparedStatement pstmt = conn.prepareStatement(inssql);
    pstmt.setInt(1, 123456);
    pstmt.setString(2, "Bougnon Kipre");
    pstmt.setString(3, "Rare Species Depatement" );
    pstmt.setDate(4, sysdate) // if this okay
    pstmt.executeUpdate();
    Alternative 2:
    String inssql =
    "insert into emp (empid, name, dept, updateDate) "+
    " values (?, ?, ?, sysdate)";
    PreparedStatement pstmt = conn.prepareStatement(inssql);
    pstmt.setInt(1, 123456);
    pstmt.setString(2, "Bougnon Kipre");
    pstmt.setString(3, "Rare Species Depatement" );
    pstmt.executeUpdate();

    Hi,
    The second alternative will be the best way.
    Since the alternative 1 won't work. sysdate cannot be accessed
    from java as a variable. Either use alternative two or create a
    java.sql.Date and insert it.
    Regards
    Elango

  • Using preparedStatement.

    Hi, in the tutorial, it only shows updating of the database sql. Can I use preparedStatement to retrieve data from the database using the SELECT sql?

    Yes.

  • AbstractMethodError while calling PreparedStatement.setBinaryStream()

    I am getting AbstractMethodError while calling PreparedStatement.setBinaryStream(int, InputStream) for a BLOB column
    I am using Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit
    JDBC Driver ojdbc6.jar (downloaded from oracle website corresponding to 11.2.0.2 version)
    JDK 6
    I understand this error is due to my code calling abstract method which is not available in JDBC 3.x and it requires JDBC 4.0
    But I am not able to find any traces of usage of earlier version of driver.
    Debugging steps performed with results are as below
    1) I enabled -verbose:class VM argument that outputs all the classes loaded along with jar from which it loads. Everywhere i see ojdbc6.jar (No reference to older or any other jdbc driver jar file)
    2) Below is code segment and its output
    Connection con = getConnection(); // get connection
    DatabaseMetaData d= con.getMetaData();
    d.getDatabaseProductName(); // output: Oracle
    d.getDatabaseProductVersion(); // output: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    d.getDatabaseMajorVersion(); // output: 11
    d.getDatabaseMinorVersion(); // output: 2
    d.getDriverName(); // output: Oracle JDBC driver
    d.getDriverVersion(); // output: 11.2.0.2.0
    d.getDriverMajorVersion(); // output: 11
    d.getDriverMinorVersion(); // output: 2
    d.supportsGetGeneratedKeys(); // output: true
    3) I updated code (its third party component, so not suppose to update :( )
    Added third argument whick works fine (it means at runtime it is using older jdbc driver???)
    PreparedStatement.setBinaryStream(int, InputStream, (int)length
    Please let me know if i am missing anything here... how can i solve this issue?
    Thanks!

    From my initial post
    I am getting AbstractMethodError while calling PreparedStatement.setBinaryStream(int, InputStream) for a BLOB column
    3) I updated code (its third party component, so not suppose to update )
    Added third argument whick works fine (it means at runtime it is using older jdbc driver???)(3) will not work if correct ojdbc6.jar is used. Because third argument is int and not long. long will work with ojdbc6 but will not work with older version.
    I am using third party component and they are using - PreparedStatement.setBinaryStream(int, InputStream)
    It should work with JDK 6, Oracle 11g and ojdbc6.jar driver.
    I am sure its simple classpath issue or some configuration mismatch - just couldn't see it right now.
    I will probably create new workspace / or test on other system now
    Thanks!

Maybe you are looking for

  • Sales order with reference of a Quotation

    Hi all, When I create a sales order (OR) with reference of a Quotation (QT), the Sold-to party of the sales order is not editable. How can I make it editable (sometime I need to change it)? Thanks in advance. Ricard.

  • 1520 not connecting to Bose 2 bluetooth headset

    I am switching from a 920 to a 1520 and my Bose 2 bluetooth headsets are not pairing (I have 2 different ones).  I have connected the 1520 to a Bose Soundlink Mini, so it connects to that.  But I do not want to purchase new BT earpieces so I am wande

  • Setting in VKOA for New GL Account

    Hi SAP Experts, We have a requirement were user has given 2 new GL accounts which should be replaced with the old GL accounts. This is has to be done for 2 materials which had differnct Plant. The scenario is such that both the materials with the old

  • What setting should I use for exporting movies?

    Hi I've read quite a lot of posts on these forums - I am getting the dreaded whitespace instead of the movie I want to see on my webpage. I created an flv from Premier Pro, put it in Flash CS3 + exported a SWF. the SWF plays fine in Flashplayer 9 and

  • Logic Pro keeps on crashing at start up

    I upgraded from Panther 10.3.9 to Tiger 10.4.2 on my iBook G4 1,33 Ghz. Now, whenever I want to start Logic Pro it just crashes. It does this each time. I tried disconnecting all my other USB devices, except the XSkey but that didn't help. I removed