Oracle 8i setAutoCommit(false) is ignored

When getting a Connection object from the Oracle 8i driver manager, I call conn.setAutoCommit(false). That should mean that if I don't explicitly call conn.commit() at the end of my INSERT/DELETE/UPDATE and before conn.close(), then the default behaviour should be for changes to be rolled back - right ? It certainly works that way with DB2.
However, I realised yesterday that I'd been forgetting to put the call to conn.commit() in my code. Regardless of this, data was still being committed. I'm confused...
I've heard tell that it is possible for an Oracle database instance to exhibit behaviour whereby data is automatically committed when a connection is closed and that, in effect, this overrides any call to setAutoCommit(false) from JDBC. I've put this question to my DBA, but am still awaiting a reply.
In the meantime, does any Oracle JDBC guru out there know why this might be happening ? I'm not messing around with transaction isolation levels.

I also found this particularly interesting (again from the Oracle JDBC manual), and probably still on the topic.
Close the Result Set and Statement Objects
You must explicitly close the ResultSet and Statement objects after you finish using them. This applies to all ResultSet and Statement objects you create when using the Oracle JDBC drivers. The drivers do not have finalizer methods; cleanup routines are performed by the close() method of the ResultSet and Statement classes. If you do not explicitly close your ResultSet and Statement objects, serious memory leaks could occur. You could also run out of cursors in the database. Closing a result set or statement releases the corresponding cursor in the database.
For example, if your ResultSet object is rset and your Statement object is stmt, close the result set and statement with these lines:
rset.close();
stmt.close();
When you close a Statement object that a given Connection object creates, the connection itself remains open.
------------------------------------------------------------------------Note:
Typically, you should put close() statements in a finally clause.

Similar Messages

  • Need information regarding setAutoCommit(false) in oracle otd

    Hi All,
    I need to insert data to two oracle tables. If data insertion to both tables are success then connection should commit else it should not commit.
    Hence for this i set
    1) oracleOtd.setAutoCommit(false);
    The i inserted value to first table. During insertion to second table it
    gave exception for me.
    But when i checked database the data has been inserted to database
    even though there is an exception.
    I believe this oracleOtd.setAutoCommit(false) doesn't have any effect.
    Please leet me know if i need to do some additional settings.
    Regards
    Venkatesh.S

    I use this same function (using JavaCAPS 5.1.1) and, admittedly, the opportunity to "test" this hasn't come up.
    However, consider putting a rollback call in your catch-block.
    oracleOtd.rollback();Dave

  • JDBC connection.setAutoCommit(false) commits after each update????

    The problem is on AUTO COMMIT of JDBC connection.
    What I did was:
    conn.setAutoCommit(false);
    conn.executeUpdate( mySQLStatement );
    conn.rollback();
    The expected result to the database table
    should be: NOTHING UPDATED.
    But what actually happened was: the updates
    went into the database.
    So the setAutoCommit(false) didn't work
    as expected.
    BTW, I am using Oracle 8.1.7 and the Oracle
    thin JDBC driver.
    Any help or hint will be appreciated.
    Thanks.
    Chenglin

    Chenglin,
    I ran the below java class on our SUN [sparc] Solaris 7 computer with J2SE 1.4.2_02, Oracle 8i (8.1.7.4) database and the "classes12.zip" file that comes with the database distribution. I checked the column value -- using SQL*Plus -- before and after running the java class, and the value was the same.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class JdbcTes2 {
      public static void main(String[] args) {
        final String SQL = "update "              +
                              "TABLE "            +
                           "set "                 +
                              "COLUMN = 'Value' " +
                           "where "               +
                              "PRIMARY_KEY = 'key'";
        Connection dbConn = null;
        Statement stmt = null;
        String line = null;
        String url = "???";
        try {
          Class.forName("oracle.jdbc.driver.OracleDriver");
          dbConn = DriverManager.getConnection(url);
          dbConn.setAutoCommit(false);
          stmt = dbConn.createStatement();
          stmt.executeUpdate(SQL);
          dbConn.rollback();
        catch (Exception x) {
          System.err.println("Exception caught: " + x);
          x.printStackTrace();
        finally {
          if (stmt != null) {
            try {
              stmt.close();
            catch (Exception x) {
              System.err.println("Failed to close statement.");
              x.printStackTrace();
          if (dbConn != null) {
            try {
              dbConn.close();
            catch (Exception x) {
              System.err.println("Failed to close DB connection.");
              x.printStackTrace();
    }Good Luck,
    Avi.

  • SetAutoCommit(false) is still committing

    Hello, I am calling a CallableStatement on an Oracle DB using JDBC connectivity by doing the following:
    Connection conn = DatabaseConnectionUtil.getConnection();
    try {
    logger.debug("Turning off auto commit");
    conn.setAutoCommit(false);
    catch (SQLException sqle) {
    logger.error("Failed to set autocommit to false on Connection object");
    logger.error(sqle);
    qo.prepareCallableStatement(conn, proc);
    qo.executeStatement();
    conn.close();
    Notice I am issuing no commits anywhere because I am just trying to test this out. However, my transactions are being committed somehow. There are no commits issued in my called package either. Is there some other setting I need to check? Is a commit done when I issue conn.close()?

    Nothing to do with setAutoCommit.
    Oracle (and some other databases) will commit on connection close; this and the contrary behaviour (rollback) are both permitted by the JDBC standard.
    You can see this in SQL*Plus too. Do an insert/update/delete, then use the "EXIT" or "DISCONNECT" commands to normally terminate your session. Connect again and you will see the changes have been committed. However, Oracle will roll back if the connection is "broken", either in SQL*Plus or in JDBC.

  • Perform transaction in creator [SetAutocommit(false) and commit()]

    Hi,
    I've finished one application with the Sun Java Studio Creator 2 but I've 2 technicals problems. One problem is about manage transactions.
    In a validate button, I've to perform update with 2 tables for example (orders and orders_details).
    My code:
    ordersDataProvider.getCachedRowSet().acceptChanges();
    orders_detailsDataProvider.getCachedRowSet().acceptChanges();
    It works but when I've an error in the 'orders_detailsDataProvider.getCachedRowSet().acceptChanges();', the orders's changes into the database are not rollback.
    I try the following:
    try{
    Context ctx=new InitialContext();
    DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/moduleachat");
    //Get a connection
    conn=ds.getConnection();
    /* Begin the transaction */
    conn.setAutoCommit(false);
    //update orders
    ordersDataProvider.getCachedRowSet().acceptChanges();
    //update order details
    orders_detailsDataProvider.getCachedRowSet().acceptChanges();
    /* Commit transaction */
    conn.commit();
    return "confirmPage";
    }catch(Exception ex){
    log(ex.getMessage(), ex);
    //Rollback transaction
    try{
    conn.rollback();
    }catch(SQLException esql){
    log(esql.getMessage(), esql);
    return null;
    it doesn't work. When errors occurs in the orders_details's update, the orders's update is not still rollback. it seems like the connection I get is not in the same context of orders and orders details rowset context.
    Can anyboby gives me a solution. It very important for a professional application

    I don't understand why nobody has solutions about my problems.
    To creator team:
    Tell us if it's a bug or not. I've try with 'acceptchanges(Connection conn)' but it doesn't work.
    Yesterday i've searched for many hours solutions on internet and I've found that others guys have the same problem and in the CachedRowSet implementation there is a property called 'COMMIT_ON_ACCEPT_CHANGE'. This property is final and set to true. i don't see where we can set it to false. So every time we call acceptchanges(connection), even if connection is in setAutoCommit ( false ), the acceptchanges commit all changes directly. Is it a bug or not? I hope no because manage transactions must be one feature of Java Studio Creator's CachedRowSet.
    Thanks

  • Error on setAutoCommit(false)

    Hi. I'm trying to do a update in my Java Web aplication, but when I get my connection and
    try to do a setAutoCommit(false) in it, I get a exception whith the message: ORA-01722: invalid number exception. The problem is this don't happens in my database, only in the database of the network where i deploy my aplication.
    Maybe is a difference between the configuration of this two databases?

    Hi. I'm trying to do a update in my Java Web aplication, but when I get my connection and
    try to do a setAutoCommit(false) in it, I get a exception whith the message: ORA-01722: invalid number exception. The problem is this don't happens in my database, only in the database of the network where i deploy my aplication.
    Maybe is a difference between the configuration of this two databases?

  • SetAutoCommit(false) fails

    I am trying to set AutoCommit to 'false'
    in a method and I get this error mesage:
    [Microsoft][ODBC Microsoft Access Driver]Attribute cannot be set now
    The message is very uninformative and frustrating.
    Has anybody encountered this before?

    This not a servlet. not EJB, just some proxy class
    for convenient database access.
    I am writing a method that takes a collection of SQL queries
    (Strings) and executes them as a single transaction:
    public String executeTransaction(Collection update_queries) throws SQLException
    if (update_queries == null)
    throw new SIException("null update queries collection passed to DBProxy.executeTransaction!");
    synchronized(_proxy_lock)
    String result = null;
    Statement update_stmnt = null;
    try
    //Enter transaction mode
    _connection.setAutoCommit(false);
    update_stmnt = _connection.createStatement();
    At the end of the method I would like to return to AutoCommit mode.
    I'd be very grateful if you could help.
    Maybe I should switch to another database provider, like PostgreSQL?

  • Oracle 10g R2 for Windows ignores init.ora and registry values

    Hello,
    I have a strange issue. I try to set some parameters for Oracle but it doesn't seem to work.
    Here the story:
    I created the DB with the DBCA under windows and set my init parameter at frist creation with 3 important values:
    OS_AUTHENT_PREFIX = ""
    REMOTE_OS_AUTHENT=TRUE
    remote_login_passwordfile=EXCLUSIVE
    this values are in the Registry and the init.ora and the init.ora.7192011143454 in ORAHOME_DB/scripts and pfile
    I've now changed these parameters in the init.ora and registry to:
    OS_AUTHENT_PREFIX = ""
    REMOTE_OS_AUTHENT=FALSE
    remote_login_passwordfile=EXCLUSIVE
    and restarted the whole system - after the restart I checked the value for REMOTE_OS_AUTHENT:
    show parameter remote_os_authent
    NAME TYPE VALUE
    remote_os_authent boolean TRUE
    It keeps true. But why it keeps true why I can't change this value anymore after the DBCA?
    Do I miss something?
    Thanks
    Edited by: ioGLNX on 22.08.2011 04:18

    show parameter spfile;
    NAME TYPE VALUE
    spfile string C:\ORACLE\PRODUCT\10.2.0\DB_1\DATABASE\SPFILEMACSCURR.ORA
    NAME TYPE VALUE
    I have created a new spfile from my init.ora with:
    create spfile='C:\oracle\product..toMyInstanceDbs\ioglnx.ora' from pfile='C:\pathToPfile\DBHOME\scripts\init.ora'
    So the problems as it seem to me to instrcut oracle to use my new spfile...in Windows.

  • Oracle 10g XMLDB - how to ignore inline references to DTD

    Is there a way to tell oracle XMLDB to ignore validating XML that has an inline DTD declaration? I'm just want to store the XML (as XMLType) in a column. All the XML's have an inline DTD declaration but I want to ignore it. Is there a way to tell oracle to do so?
    Thanks in advance!

    Hi,
    I dont know sql server 2005. But by observing it I feel you are generating sql dynamically based on condition inside the proc.
    DECLARE
       TYPE EmpCurTyp IS REF CURSOR;
       emp_cv   EmpCurTyp;
       emp_rec  employees%ROWTYPE;
       sql_stmt VARCHAR2(200);
       v_job   VARCHAR2(10) := 'ST_CLERK';
    BEGIN
       sql_stmt := 'SELECT * FROM employees WHERE job_id = :j';
       OPEN emp_cv FOR sql_stmt USING v_job;
       LOOP
         FETCH emp_cv INTO emp_rec;
         EXIT WHEN emp_cv%NOTFOUND;
         DBMS_OUTPUT.PUT_LINE('Name: ' || emp_rec.last_name || ' Job Id: ' ||
                               emp_rec.job_id);
       END LOOP;
       CLOSE emp_cv;
    END;something like this it will be. it is in oracle documentaion
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/dynamic.htm#i14500

  • Oracle Streaming not working, -- PLEASE IGNORE

    Hello All
    I am trying to setup streaming between two databases:
    Source database = Oracle 10g 10.1.0.5
    Destination = Oracel 10g 10.2.
    I did following steps:
    1- User 'strmadmin' created on both databases granted GRANT_ADMIN_PRIVILEGE,
    2- Both have JOB_QUEUE_PROCESSES > 2
    3- At both databased db_link with name 'sttream' pointing to each other databased has been setup and working fine.
    4- executed on both: EXEC DBMS_STREAMS_ADM.SET_UP_QUEUE();
    5- At source db, supplemental log added on the desired table.
    6- At source db, following rule executed:
    BEGIN
    DBMS_STREAMS_ADM.ADD_TABLE_RULES(
    table_name => 'dba_st.sayeed_streaming',
    streams_type => 'capture',
    streams_name => 'capture_stream',
    queue_name =>
    'strmadmin.streams_queue',
    include_dml => true,
    include_ddl => true,
    inclusion_rule => true);
    END;
    7- At source db, following propogation rule done:
    BEGIN
    DBMS_STREAMS_ADM.ADD_TABLE_PROPAGATION_RULES(
    table_name      => 'dwhstream.sayeed_streaming',
    streams_name      => 'st4_to_dwh',
    source_queue_name      => 'strmadmin.streams_queue',
    destination_queue_name      => 'strmadmin.streams_queue@dwh',
    include_dml      => true,
    include_ddl      => true,
    source_database      => 'dba_st',
    inclusion_rule      => true);
    END;
    8- At destination db, table created with same name and attributes.
    9- instantiation SCN at source db as:
    DECLARE
    source_scn NUMBER;
    BEGIN
    source_scn := DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBER();
    DBMS_APPLY_ADM.SET_TABLE_INSTANTIATION_SCN@dwhstream(
    source_object_name      => 'dba_st.sayeed_streaming',
    source_database_name      => 'dba_st',
    instantiation_scn      => source_scn);
    END;
    10- At destination db:
         BEGIN
         DBMS_STREAMS_ADM.ADD_TABLE_RULES(
         table_name => 'dba_st.sayeed_streaming',
         streams_type => 'apply',
         streams_name => 'apply_stream',
         queue_name =>
         'strmadmin.streams_queue',
         include_dml => true,
         include_ddl => true,
         source_database => 'dba_st',
         inclusion_rule => true);
         END;
    11- At source db:
         BEGIN
         DBMS_CAPTURE_ADM.START_CAPTURE(
         capture_name =>
         'capture_stream');
         END;
    12- At destination DB:
    BEGIN
    DBMS_APPLY_ADM.START_APPLY(
    apply_name => 'apply_stream');
    END;
    So all this i did but when i change, insert or delet in source table, nothing comes at destination.
    Please guide me what steps i had missed or where to look errors step by step.
    Thanks in advance
    Sayeed
    Edited by: user9206270 on Mar 1, 2010 9:38 PM

    this is a duplicate post. Please change the subject to "Please ignore" Thank you.
    Your initial post was in the correct group and multiple posts is considered very bad form by most here that try to help.
    Again thank you for cleaning it up and removing this.

  • Nth_value() function with IGNORE NULLS in oracle 10g

    Is there any easy way to mimic ORACLE 11g nth_value() function with IGNORE NULLS clause in 10g or earlier Oracle release?

    SQL> select  ename,
      2          sal,
      3          nth_value(sal,5) over() fifth_min_sal
      4    from  emp
      5    order by sal
      6  /
    ENAME             SAL FIFTH_MIN_SAL
    SMITH             800           1250
    JAMES             950           1250
    ADAMS            1100           1250
    WARD             1250           1250
    MARTIN           1250           1250
    MILLER           1300           1250
    TURNER           1500           1250
    ALLEN            1600           1250
    CLARK            2450           1250
    BLAKE            2850           1250
    JONES            2975           1250
    ENAME             SAL FIFTH_MIN_SAL
    SCOTT            3000           1250
    FORD             3000           1250
    KING             5000           1250
    14 rows selected.
    SQL> select  ename,
      2          sal,
      3          min(case rn when 5 then sal end) over() fifth_min_sal
      4    from  (
      5           select  ename,
      6                   sal,
      7                   row_number() over(order by sal nulls last) rn
      8             from  emp
      9          )
    10    order by sal
    11  /
    ENAME             SAL FIFTH_MIN_SAL
    SMITH             800           1250
    JAMES             950           1250
    ADAMS            1100           1250
    WARD             1250           1250
    MARTIN           1250           1250
    MILLER           1300           1250
    TURNER           1500           1250
    ALLEN            1600           1250
    CLARK            2450           1250
    BLAKE            2850           1250
    JONES            2975           1250
    ENAME             SAL FIFTH_MIN_SAL
    SCOTT            3000           1250
    FORD             3000           1250
    KING             5000           1250
    14 rows selected.
    SQL> SY.

  • How to setAutoCommit to false in JPA2 transactions?

    I am very sorry for the multiple posting I issued, I apologized and but it didn't work apparently.
    In the rolling back from a partially failed transaction acting on several entities, gimbal2 suggested turning the autoCommit off (maybe something like setAutoCommit(false)). Any idea how one does this in JPA 2 + Eclipselink + Glassfish 3.1?
    Many thanks.

    Your DAO layer should not really get so complicated that you can't post a SSCE that demonstrates the problem, especially if you are using JPA. You are probably already manually doing too much that should be left to JPA with the right relationships and cascade types set. I really think you should use this as a warning that there is something wrong and consider simplying things before your DAO gets too complicated for any changes to be made to it. An exception always causes the current transaction to be marked for rollback as long as it's not an application exception. Either
    1.) You are using open session in view
    2.) You are calling other methods that are running in their own transaction different from the calling transaction.
    3.) You are manually forcing commits at some points in your code.
    It is extremely unlikely that there is a bug in your container's JTA implementation that is causing this.Many thanks for your time.
    To your points above.
    1) Sorry, would you be more specific to what you mean?
    2) I was, but then I eliminated all long-distance calls and made them all local! You will see below.
    3) Yes I do, but no flushing; otherwise how would I persist?
    Very well then, here is an pseude-SSCE that causes the failures I am talking about, do excuse me for being verbose (academia-inherited).
    I have the following entities for a conference management system we are building. I have:
    - Participant, any new user will become a participant in the system
    - Referee, the new user could then assume the roles of a referee, author, attendee... or a combo
    // supper class for sharing code
    @MappedSuperclass
    public abstract class ParentEntity implements Serializable {
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private Integer id;
       // other objects, setters, getters...
    // a participant in the system could assume several roles, a key-per-role however
    @Entity
    public class ZparticipantRole implements Serializable {
       @Id
       private Integer id;
    @Entity
    public class Participant extends ParentEntity {
       @OneToMany
       private List<ZparticipantRole> zparticipantRoles = new ArrayList<ZparticipantRole>();
       // other objects, setters, getters...
    @Entity
    public class Referee extends ParentEntity {
       @OneToOne
       private Participant participant = new Participant();  
       // other objects, setters, getters...
    Here is how persistence.xml looks, running on GF 3.1, NB 7, JPA 2, Eclipselink impl.
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
      <persistence-unit name="default" transaction-type="JTA">
        <jta-data-source>mysql_mecms</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <validation-mode>NONE</validation-mode>
        <properties>
        </properties>
      </persistence-unit>
    </persistence>
    // managed bean that fetches data from the frontend to dispatch for transaction management
    @ManagedBean
    @ViewScoped
    public class EventRegRefereeController implements Serializable {
       @EJB
       private JPAManager jpaManager;
       // other data, setters and getters
       // method called from JSF page
       public void regAsRef() {
          boolean statusOk = true;
          try {
             // participant is already persisted, but referee is new
             jpaManager.createReferee(referee, participant);
          } catch (Exception e) {
             statusOk = false;
          // life goes on...
    @Stateless
    public class JPAManager implements Serializable {
       @PersistenceContext(unitName = "default")
       private EntityManager em;
       final int AUTHOR_ROLE = 1;
       final int REFEREE_ROLE = 2;
       public void createReferee(Referee referee, Participant participant) {
          referee.setParticipant(participant);
          em.persist(referee);
          ZparticipantRole refereeRole = em.getReference(ZparticipantRole.class, REFEREE_ROLE);
          participant.getZparticipantRoles().add(refereeRole);
          em.merge(participant);
       // other methods...
    }So all the necessary ingredients are above. Here is what happens, and I will use code-style to preserve indentation.
      1. Database empty, a new user comes so they would be registered as a participant, call them p1 with id=1
      2. p1 comes back to register as referee,
        2.1 participant is fetched using "em.find()",
        2.2 new referee is created
        2.3 jpaManager is called on them (jpaManager.createReferee(referee, participant);)
       Since referee is brand new, all goes ok, call them r1 with id=1
      3. There is a table called participant_zparticipantrole and it has the following entry: (Participant_ID, zparticipantRoles_ID) = (1, 2)
      4. Suppose now that we execute a bad piece of code... what's better than Step 2.3 above? That is, the SAME referee on the SAME participant (just bear with me... I know that's bad and avoidable), here is what happens:
        4.1 The same referee arrives to the createReferee method, but, because the key-generation is IDENTITY, the old (id=1) is neglected and a new id=2 for the referee is created and persisted. So far, we deserve it
        4.2 The this piece is executed: participant.getZparticipantRoles().add(refereeRole)... see it? This is bad, we are putting the same record ((Participant_ID, zparticipantRoles_ID) = (1, 2)) in the same table! And it fails, rightly so.
        4.3 An exception is thrown, something like this:
    Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-2' for key 1
    Error Code: 1062
    Call: INSERT INTO PARTICIPANT_ZPARTICIPANTROLE (zparticipantRoles_ID, Participant_ID) VALUES (?, ?)
    and this statement appears in the exception:
    Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
    ...Yet, the new record inserted for the referee is never rolled back! My referee table has two entries with id=1 and id=2. This is where I was expecting a rollback. That got us worried, suppose there is a piece of a faulty logic lurking somewhere that would give way sometime due to some failure, our database is... smudged!
    So?

  • How to insert a image file into oracle database

    hi all
    can anyone guide me how to insert a image file into oracle database now
    i have created table using
    create table imagestore(image blob);
    but when inserting i totally lost don't know what to do how to write query to insert image file

    Hi I don't have time to explain really, I did have to do this a while ago though so I will post a code snippet. This is using the commons file upload framework.
    Firstly you need a multi part form data (if you are using a web page). If you are not using a web page ignore this bit.
    out.println("<form name=\"imgFrm\" method=\"post\" enctype=\"multipart/form-data\" action=\"FileUploadServlet?thisPageAction=reloaded\" onSubmit=\"return submitForm();\"><input type=\"FILE\" name=\"imgSource\" size='60' class='smalltext' onKeyPress='return stopUserInput();' onKeyUp='stopUserInput();' onKeyDown='stopUserInput();' onMouseDown='noMouseDown(event);'>");
    out.println("   <input type='submit' name='submit' value='Submit' class='smalltext'>");
    out.println("</form>"); Import this once you have the jar file:
    import org.apache.commons.fileupload.*;Now a method I wrote to upload the file. I am not saying that this is correct, or its the best way to do this. I am just saying it works for me.
    private boolean uploadFile(HttpServletRequest request, HttpSession session) throws Exception {
            boolean result = true;
            String fileName = null;
            byte fileData[] = null;
            String fileUploadError = null;
            String imageType = "";
            String error = "";
            DiskFileUpload fb = new DiskFileUpload();
            List fileItems = fb.parseRequest(request);
            Iterator it = fileItems.iterator();
            while(it.hasNext()){
                FileItem fileItem = (FileItem)it.next();
                if (!fileItem.isFormField()) {
                    fileName = fileItem.getName();
                    fileData = fileItem.get();
                    // Get the imageType from the filename extension
                    if (fileName != null) {
                        int dotPos = fileName.indexOf('.');
                        if (dotPos >= 0 && dotPos != fileName.length()-1) {
                            imageType = fileName.substring(dotPos+1).toLowerCase();
                            if (imageType.equals("jpg")) {
                                imageType = "jpeg";
            String filePath = request.getParameter("FILE_PATH");
            session.setAttribute("filePath", filePath);
            session.setAttribute("fileData", fileData);
            session.setAttribute("fileName", fileName);
            session.setAttribute("imageType", imageType);
            return result;  
         } And now finally the method to actually write the file to the database:
    private int writeImageFile(byte[] fileData, String fileName, String imageType, String mode, Integer signatureIDIn, HttpServletRequest request) throws Exception {
            //If the previous code found a file that can be uploaded then
            //save it into the database via a pstmt
            String sql = "";
            UtilDBquery udbq = getUser(request).connectToDatabase();
            Connection con = null;
            int signatureID = 0;
            PreparedStatement pstmt = null;
            try {
                udbq.setUsePreparedStatements(true);
                con = udbq.getPooledConnection();
                con.setAutoCommit(false);
                if((!mode.equals("U")) || (mode.equals("U") && signatureIDIn == 0)) {
                    sql = "SELECT SEQ_SIGNATURE_ID.nextval FROM DUAL";
                    pstmt = con.prepareStatement(sql);
                    ResultSet rs = pstmt.executeQuery();
                    while(rs.next()) {
                       signatureID = rs.getInt(1);
                    if (fileName != null && imageType != null) {
                        sql = "INSERT INTO T_SIGNATURE (SIGNATURE_ID, SIGNATURE) values (?,?)";
                        InputStream is2 = new ByteArrayInputStream(fileData);
                        pstmt = con.prepareStatement(sql);
                        pstmt.setInt(1, signatureID);
                        pstmt.setBinaryStream(2, is2, (int)(fileData.length));
                        pstmt.executeUpdate();
                        pstmt.close();
                        con.commit();
                        con = null;
                if(mode.equals("U") && signatureIDIn != 0) {
                    signatureID = signatureIDIn.intValue();
                    if (fileName != null && imageType != null) {
                        sql = "UPDATE T_SIGNATURE SET SIGNATURE = ? WHERE SIGNATURE_ID = ?";
                        InputStream is2 = new ByteArrayInputStream(fileData);
                        pstmt = con.prepareStatement(sql);
                        pstmt.setBinaryStream(1, is2, (int)(fileData.length));
                        pstmt.setInt(2, signatureID);
                        pstmt.executeUpdate();
                        pstmt.close();
                        con.commit();
                        con = null;
            } catch (Exception e) {
                con = null;
                throw new Exception(e.toString());
            return signatureID;
       }

  • Urgent help (on oracle connection pool)

    Hi ,
    I downloade oracle 8i thin drivers and i am using conenction pool in my application ...
    I executed that servlet program
    When i try to get conneciton using getDatabaseConnection() method in my jsp i am getting new connection each time ...............
    In the oracel doc i read some thing like logical connections and physical connections .............
    In my code i set maxLimit to 3 and i am getting connections more than 3 ( all are different).................
    When i refresh the browser i am getting different connections like:
    con======oracle.jdbc.driver.OracleConnection@338576
    con======oracle.jdbc.driver.OracleConnection@1691dec
    con======oracle.jdbc.driver.OracleConnection@63ceb4
    con======oracle.jdbc.driver.OracleConnection@1590f50
    con======oracle.jdbc.driver.OracleConnection@aeff82
    con======oracle.jdbc.driver.OracleConnection@906e5b
    con======oracle.jdbc.driver.OracleConnection@2403cf
    con======oracle.jdbc.driver.OracleConnection@17ab157
    See i set max limit as 3 and i got more than 3 connections and each diff ................
    What is wrong in my code ............
    Please help to me ..........
    Here is the code :
    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.jdbc.pool.*;
    public class PoolJdbc4 extends HttpServlet{
    private OracleConnectionPoolDataSource ocpds;
    private OracleConnectionCacheImpl ods;
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {
    ocpds =new OracleConnectionPoolDataSource();
    ocpds.setURL("jdbc:oracle:xxxxxxxxx");
    // ocpds.setUser("xxx");
    // ocpds.setPassword("xxx");
    // Associate it with the Cache
    ods = new OracleConnectionCacheImpl(ocpds);
    // Set the Max Limit
    ods.setMaxLimit (3);
    // Set the Scheme
    ods.setCacheScheme (OracleConnectionCacheImpl.FIXED_RETURN_NULL_SCHEME);
    catch (Exception e) {
    throw new UnavailableException(this, "Couldn't create connection pool");
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    Connection con = null;
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    out.println("Updating salary");
    try {
    con = ods.getConnection("xxxxx","xxx");
    System.out.println("con======="+con);
    // Turn on transactions
    con.setAutoCommit(false);
    Statement stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery("select * from checkout_checkin");
    while(rs.next())
    out.println(rs.getString(1)+"<br>");
    stmt.close();
    rs.close();
    con.close();
    catch (Exception e) {
    // Any error is grounds for rollback
    try {
    con.rollback();
    catch (Exception ignored) { }
    out.println("No more connections available, try later");
    }

    ketan reddy - I'm pretty sure you are not getting a new connection each time even though you are seeing a different connection identifier printed each time you get a new connection.
    If you have system privs, try looking at v$session while your servlet is running. I think you will see that you only have a single connection and it is being used each time.
    For another test, try commenting out your conn.close() call so that you do not free up connections. Your servlet should fail after 3 executions cause it will not be able to get any more connections - because you specified
    ods.setMaxLimit (3);
    ods.setCacheScheme (OracleConnectionCacheImpl.FIXED_RETURN_NULL_SCHEME);
    Good Luck
    tim

  • Oracle Batch Inserts--

    hello folks...
    before procceding furthur I would like to thank the people who have helped me till date on this forumn..without whose help I would not have held on to my job.Thanks
    I am wking on Oracle batch statements inorder to improove the efiicienecy of Inserts that run into millions of records.I have been able to improove the efficiency a lot by doing so (around 20-25%)
    I have a feeling that I could improove the efficiency furthur by playing around with the number of Inserts done per batch.Presently I batch them arbitarily whenever certain criretia is met ( sometimes it is more than a 1000 inserts sometimes it is less than 10).
    I have read a lot of articles on batching and searched this forumn too ...but I am not too certain where I should draw the line .on whether to use a batch or a normal insertion.
    Since the data I am wking on(Biological data ) is too complicated to do create a test data and since the whole process takes in excess of 16 hrs it is difficult for me to do many arbitary testing (try different combinations of batch sizes) .
    What I am looking for is "in a genearl in case" what MIGHT be a good batch size....
    I know this is a bit too vague and there may no specific number ...I would appreciate your thoughts and views on it
    Thanks for your time

    How many ms/insert do you get in your productionprogram?
    I have not tested them individually by say a batch but
    that is a good idea.to calculate the rate .Ballpark? "Program run with 1,000,000 inserts takes about half an hour"?
    Inspired by the O'Reilly book chapter you showed, I tried PreparedStatement (program below). PreparedStatement seems way faster than a plain Statement, and scales better:
    batch size 1 best time 25 = 120 insert/s
    batch size 10 best time 21 = 1428 insert/s
    batch size 50 best time 31 = 4838 insert/s
    batch size 100 best time 37 = 8108 insert/s
    batch size 500 best time 341 = 4398 insert/s
    batch size 1000 best time 401 = 7481 insert/s
    batch size 2000 best time 203 = 29556 insert/s
    batch size 3000 best time 339 = 26548 insert/s
    batch size 4000 best time 409 = 29339 insert/s
    batch size 5000 best time 498 = 30120 insert/s
    batch size 6000 best time 725 = 24827 insert/sMaxes out with a batch size of around 2000 at 30,000 inserts a second -- that's way more than I'd have thought possible! I've never done batching, only round-trip queries, so this is all new to me.
    ...Can anyone see a bug in the code below? I'm getting some weird results with batched PS's on Oracle: if a PS doesn't have any "?" parameters, just a constant insert statement, seems like addBatch() doesn't execute all the statements?? Replace the "?" with "1" and remove the setInt() call. I'm not the first to shout Java Is Broken, but here I have half a mind to say there's a bug in the Oracle driver here...
    import java.sql.DriverManager;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    public class demo4
        static Connection connection;
        public static void main(String args[])
            try {
                DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                connection = DriverManager.getConnection(args[0], args[1], args[2]);
                // Let the JIT compiler warm up a bit first
                doit(100);
                doit(100);
                doit(100);
                doit(1);
                doit(10);
                doit(50);
                doit(100);
                doit(500);
                doit(1000);
                doit(2000);
                doit(3000);
                doit(4000);
                doit(5000);
                doit(6000);
            } catch (Exception e) {
                System.err.println("exception in db test: " + e);
                e.printStackTrace(System.err);
        private static void doit(int batch_size)
            throws SQLException
            long best = -1;
            clearTable();
            int rounds = batch_size * 3;
            for (int n = 0; n < 5; n++) {
                long time = batch(batch_size, rounds);
                if (best == -1 || time < best)
                    best = time;
            System.out.println("batch size " + batch_size +
                               " best time " + best +
                               " = " + ((rounds * 1000) / best) +
                               " insert/s");
        private static void clearTable()
            throws SQLException
            Statement stmt = connection.createStatement();
            try {
                stmt.executeUpdate("drop table demo4");
            } catch (SQLException e) {
                // Ignore, it's just saying "table does not exist"
            stmt.executeUpdate("create table demo4 (" +
                               " a number(10)," +
                               " b number(10)," +
                               " c varchar(20)" +
            connection.commit();
            Util.close(stmt);
        private static long batch(int batch_size, int rounds)
            throws SQLException
            long start_time = System.currentTimeMillis();
            connection.setAutoCommit(false);
            String sql = "insert into demo4 values (?, 2, 'hello')";
            PreparedStatement stmt = connection.prepareStatement(sql);
            for (int n = 0; ; n++) {
                if (n == rounds || (n % batch_size == 0 && n != 0)) {
                    int counts[] = stmt.executeBatch();
                    for (int x = 0; x < counts.length; x++)
                        System.out.println("count " + x + " = " + counts[x]);
                    connection.commit();
                    stmt.clearBatch();
                    if (n == rounds)
                        break;
                stmt.setInt(1, n);
                stmt.addBatch();
            Util.close(stmt);
            long end_time = System.currentTimeMillis();
            long time = end_time - start_time;
            System.out.println("batch size " + batch_size +
                               " time: " + time + " ms");
            return time;
        public static class Util
            public static void close(Statement s)
                if (s == null)
                    return;
                try {
                    s.close();
                } catch (Exception e) {
                    System.err.println("Util.close: error closing Statement: " + e);

Maybe you are looking for

  • Why are most of the links on Oracle's site that relate to Java broken?

    Why are most of the links on Oracle's site that relate to Java broken? For example, try searching for SocketChannel and then clicking on any of the returned links, in particular click on www.oracle.com/technetwork/servers-storage/ts-4222-159193.pdf.

  • IWeb suddenly quits/crashes

    Suddenly iWeb keeps quitting on me when I go to make an adjustment.  Is this something to do with a cache or preference file or what?  Do I need to reinstall iWeb?  Thanks to anyone who can help.  Here is the report: Process:         iWeb [5295] Path

  • Paper Jam indicator without a paper jam in a OfficeJet L7590

    I need to know how to reset the printer after there is a phantom paper jam indication. The printer "will not clear" so I can resume printing. Thanks

  • What's going on with this site

    Hi, I've made this page for a client some time ago http://munck-feldthusen.dk/ and it works just fine. Today I got a call from him saying that he bought another name... this one http://www.glarmesterservice.dk/ which he asked his host to point to the

  • How to install rpm's on OEL with automatic dependency resolving

    Hi there, I am using OEL 5.5. Is there a way to install RPM with automatic dependency resolution? I mean, if the the RPM being installed needs one or more other (and maybe one of those RPMs also have dependencies), is there a way to tell OEL to autom