protected void assertBackPointers(Connection conn, Statement statement) throws SQLException {
    assertFalse(conn.isClosed());
    assertFalse(isClosed(statement));

    assertSame(
        "statement.getConnection() should return the exact same connection instance that was used to create the statement",
        conn,
        statement.getConnection());

    ResultSet resultSet = statement.getResultSet();
    assertFalse(isClosed(resultSet));
    assertSame(
        "resultSet.getStatement() should return the exact same statement instance that was used to create the result set",
        statement,
        resultSet.getStatement());

    ResultSet executeResultSet = statement.executeQuery("select * from dual");
    assertFalse(isClosed(executeResultSet));
    assertSame(
        "resultSet.getStatement() should return the exact same statement instance that was used to create the result set",
        statement,
        executeResultSet.getStatement());

    ResultSet keysResultSet = statement.getGeneratedKeys();
    assertFalse(isClosed(keysResultSet));
    assertSame(
        "resultSet.getStatement() should return the exact same statement instance that was used to create the result set",
        statement,
        keysResultSet.getStatement());

    ResultSet preparedResultSet = null;
    if (statement instanceof PreparedStatement) {
      PreparedStatement preparedStatement = (PreparedStatement) statement;
      preparedResultSet = preparedStatement.executeQuery();
      assertFalse(isClosed(preparedResultSet));
      assertSame(
          "resultSet.getStatement() should return the exact same statement instance that was used to create the result set",
          statement,
          preparedResultSet.getStatement());
    }

    resultSet.getStatement().getConnection().close();
    assertTrue(conn.isClosed());
    assertTrue(isClosed(statement));
    assertTrue(isClosed(resultSet));
    assertTrue(isClosed(executeResultSet));
    assertTrue(isClosed(keysResultSet));
    if (preparedResultSet != null) {
      assertTrue(isClosed(preparedResultSet));
    }
  }
Beispiel #2
1
    /** 从连接池获得一个可用连接.如没有空闲的连接且当前连接数小于最大连接 数限制,则创建新连接.如原来登记为可用的连接不再有效,则从向量删除之, 然后递归调用自己以尝试新的可用连接. */
    public synchronized Connection getConnection() {
      Connection con = null;
      if (freeConnections.size() > 0) {
        // 获取向量中第一个可用连接
        con = (Connection) freeConnections.firstElement();
        freeConnections.removeElementAt(0);
        try {
          if (con.isClosed()) {
            System.out.println("从连接池" + id + "删除一个无效连接");
            System.out.println("从连接池" + id + "删除一个无效连接");
            // 递归调用自己,尝试再次获取可用连接
            con = getConnection();
          }
        } catch (SQLException e) {
          System.out.println("从连接池" + id + "删除一个无效连接时错误");
          System.out.println("从连接池" + id + "删除一个无效连接出错");
          // 递归调用自己,尝试再次获取可用连接
          con = getConnection();
        }
        if (freeConnections.size() > maxConn) {
          System.out.println(" 删除一个溢出连接 ");
          releaseOne();
        }
      } else if ((maxConn == 0) || (freeConnections.size() < maxConn)) {
        con = newConnection();
      }

      return con;
    }
Beispiel #3
1
    public synchronized Connection returnConnection() {
      Connection con = null;
      // 如果闲置小于最大连接,返回一个新连接
      if (freeConnections.size() < maxConn) {
        con = newConnection();
      }
      // 如果闲置大于最大连接,返回一个可用的旧连接
      else if (freeConnections.size() >= maxConn) {

        con = (Connection) freeConnections.firstElement();
        System.out.println(" [a 连接池可用连接数 ] : " + "[ " + freeConnections.size() + " ]");
        freeConnections.removeElementAt(0);
        System.out.println(" [b 连接池可用连接数 ] : " + "[ " + freeConnections.size() + " ]");
        try {
          if (con.isClosed()) {
            System.out.println("从连接池" + id + "删除一个无效连接");
            System.out.println("从连接池" + id + "删除一个无效连接");
            returnConnection();
          }
        } catch (SQLException e) {
          System.out.println("从连接池" + id + "删除一个无效连接时错误");
          System.out.println("从连接池" + id + "删除一个无效连接出错");
          returnConnection();
        }
      }
      return con;
    }
 @Test
 public void testRegister() throws Exception {
   final Connection connection = DriverManager.getConnection("jdbc:avatica:remote:");
   assertThat(connection.isClosed(), is(false));
   connection.close();
   assertThat(connection.isClosed(), is(true));
 }
 @Test
 public void testMetaFunctionsLocal() throws Exception {
   final Connection connection = CalciteAssert.hr().connect();
   assertThat(connection.isClosed(), is(false));
   for (Meta.DatabaseProperty p : Meta.DatabaseProperty.values()) {
     switch (p) {
       case GET_NUMERIC_FUNCTIONS:
         assertThat(connection.getMetaData().getNumericFunctions(), not(equalTo("")));
         break;
       case GET_SYSTEM_FUNCTIONS:
         assertThat(connection.getMetaData().getSystemFunctions(), CoreMatchers.notNullValue());
         break;
       case GET_TIME_DATE_FUNCTIONS:
         assertThat(connection.getMetaData().getTimeDateFunctions(), not(equalTo("")));
         break;
       case GET_S_Q_L_KEYWORDS:
         assertThat(connection.getMetaData().getSQLKeywords(), not(equalTo("")));
         break;
       case GET_STRING_FUNCTIONS:
         assertThat(connection.getMetaData().getStringFunctions(), not(equalTo("")));
         break;
       default:
     }
   }
   connection.close();
   assertThat(connection.isClosed(), is(true));
 }
  /**
   * This method tests the functionality of connection in high stress.
   *
   * @throws Exception if any error occurs.
   */
  public void testStressForConnection() throws Exception {

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < COUNT; ++i) {
      Connection conn = null;
      try {
        conn =
            new DBConnectionFactoryImpl(DBConnectionFactoryImpl.class.getName()).createConnection();
        conn.setAutoCommit(false);
        StressHelper.doDMLQuery(conn, QUERY1, new Object[] {});
        persistence.closeConnection(conn);
        assertTrue("Fails to close the connection.", conn.isClosed());
        conn =
            new DBConnectionFactoryImpl(DBConnectionFactoryImpl.class.getName()).createConnection();
        conn.setAutoCommit(true);
        Object[][] rows =
            StressHelper.doQuery(
                conn, QUERY2, new Object[] {}, new DataType[] {StressHelper.STRING_TYPE});
        assertEquals("Fails to commit the changes in database.", "property 1", rows[0][0]);
        StressHelper.doDMLQuery(conn, QUERY3, new Object[] {});
        conn.close();
      } finally {
        if (conn != null && !conn.isClosed()) {
          conn.close();
        }
      }
    }

    long endTime = System.currentTimeMillis();
    System.out.println(
        "The stress test for connection costs: " + (endTime - startTime) + " milliseconds.");
  }
 @Test
 public void destroy_shouldCloseAllConnections2() throws SQLException {
   Connection c1 = connectionPool.reserveConnection();
   Connection c2 = connectionPool.reserveConnection();
   connectionPool.releaseConnection(c1);
   connectionPool.releaseConnection(c2);
   connectionPool.destroy();
   Assert.assertTrue(c1.isClosed());
   Assert.assertTrue(c2.isClosed());
 }
  @Test
  public void testConnection() throws Exception {
    Connection conn = getConnection();

    assertNull(conn.getMetaData());

    assertFalse(conn.getAutoCommit());
    conn.setAutoCommit(true);
    assertTrue(conn.getAutoCommit());
    conn.setAutoCommit(false);

    assertTrue(conn.isReadOnly());
    conn.setReadOnly(true);
    assertTrue(conn.isReadOnly());

    assertEquals(Connection.TRANSACTION_NONE, conn.getTransactionIsolation());
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn.getTransactionIsolation());
    conn.setTransactionIsolation(Connection.TRANSACTION_NONE);

    assertNull(conn.getWarnings());
    conn.clearWarnings();

    assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability());
    conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
    assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
    conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);

    conn.commit();
    conn.rollback();

    assertTrue(conn.isValid(0));

    conn.setClientInfo("prop1", "value1");
    Properties props = new Properties();
    props.setProperty("prop2", "value2");
    props.setProperty("prop3", "value3");
    conn.setClientInfo(props);
    assertEquals("value1", conn.getClientInfo("prop1"));
    assertEquals("value2", conn.getClientInfo("prop2"));
    assertEquals("value3", conn.getClientInfo("prop3"));
    Properties props2 = conn.getClientInfo();
    assertEquals("value1", props2.getProperty("prop1"));
    assertEquals("value2", props2.getProperty("prop2"));
    assertEquals("value3", props2.getProperty("prop3"));

    assertNotNull(((JcrJdbcConnection) conn).getJcrSession());

    assertFalse(conn.isClosed());
    conn.close();
    assertTrue(conn.isClosed());
  }
Beispiel #9
0
 /** * 批量修改线路名称 */
 @Action(
     value = "changeLineName",
     results = {@Result(type = "json")})
 public String changeLineName() throws Exception {
   Connection conn = null;
   String sql = null;
   try {
     conn = MyDataSource.getConnect();
     conn.setAutoCommit(false);
     QueryRunner qr = new QueryRunner();
     sql = " SELECT newName AS a1,oldName AS a2 FROM sheet1 ";
     List<AppVo_2> list = qr.query(conn, sql, new BeanListHandler<AppVo_2>(AppVo_2.class));
     if (null != list && list.size() > 0) {
       AppVo_2 vo = new AppVo_2();
       Object[] args = null;
       for (int i = 0; i < list.size(); i++) {
         vo = list.get(i);
         sql = " UPDATE line_base_info SET lineName= ? WHERE lineName = ? ";
         args = new Object[2];
         args[0] = vo.getA1();
         args[1] = vo.getA2();
         qr.update(conn, sql, args);
       }
     }
     getResponse().getWriter().print("success");
     conn.commit();
   } catch (Exception e) {
     e.printStackTrace();
     try {
       if (null != conn && conn.isClosed() == false) {
         try {
           conn.rollback();
         } catch (SQLException e1) {
           e1.printStackTrace();
         }
       }
     } catch (SQLException e1) {
       getResponse().getWriter().print("error");
       e1.printStackTrace();
     }
   } finally {
     try {
       if (null != conn && conn.isClosed() == false) {
         conn.setAutoCommit(true);
         conn.close();
       }
     } catch (SQLException e) {
       e.printStackTrace();
     }
   }
   return null;
 }
 /**
  * Verify the close method can be called multiple times on a single connection without an
  * exception being thrown.
  */
 public void testCanCloseConnectionTwice() throws Exception {
   for (int i = 0;
       i < getMaxActive();
       i++) { // loop to show we *can* close again once we've borrowed it from the pool again
     Connection conn = newConnection();
     assertNotNull(conn);
     assertTrue(!conn.isClosed());
     conn.close();
     assertTrue(conn.isClosed());
     conn.close();
     assertTrue(conn.isClosed());
   }
 }
  @Override
  public Connection getConnection() throws SQLException {
    if (!CurrentUnitOfWork.isStarted()
        || CurrentUnitOfWork.get().phase().isAfter(UnitOfWork.Phase.PREPARE_COMMIT)) {
      return delegate.getConnection();
    }

    UnitOfWork<?> uow = CurrentUnitOfWork.get();
    Connection connection = uow.root().getResource(CONNECTION_RESOURCE_NAME);
    if (connection == null || connection.isClosed()) {
      final Connection delegateConnection = delegate.getConnection();
      connection =
          ConnectionWrapperFactory.wrap(
              delegateConnection,
              UoWAttachedConnection.class,
              new UoWAttachedConnectionImpl(delegateConnection),
              new ConnectionWrapperFactory.NoOpCloseHandler());
      uow.root().resources().put(CONNECTION_RESOURCE_NAME, connection);
      uow.onCommit(
          u -> {
            Connection cx = u.root().getResource(CONNECTION_RESOURCE_NAME);
            try {
              if (!cx.isClosed() && !cx.getAutoCommit()) {
                cx.commit();
              }
            } catch (SQLException e) {
              throw new JdbcException("Unable to commit transaction", e);
            }
          });
      uow.onCleanup(
          u -> {
            Connection cx = u.root().getResource(CONNECTION_RESOURCE_NAME);
            JdbcUtils.closeQuietly(cx);
            if (cx instanceof UoWAttachedConnection) {
              ((UoWAttachedConnection) cx).forceClose();
            }
          });
      uow.onRollback(
          u -> {
            Connection cx = u.root().getResource(CONNECTION_RESOURCE_NAME);
            try {
              if (!cx.isClosed() && !cx.getAutoCommit()) {
                cx.rollback();
              }
            } catch (SQLException ex) {
              throw new JdbcException("Unable to rollback transaction", ex);
            }
          });
    }
    return connection;
  }
 @Test
 public void testCatalogsLocal() throws Exception {
   final Connection connection = DriverManager.getConnection("jdbc:avatica:remote:factory=" + LJS);
   assertThat(connection.isClosed(), is(false));
   final ResultSet resultSet = connection.getMetaData().getCatalogs();
   final ResultSetMetaData metaData = resultSet.getMetaData();
   assertThat(metaData.getColumnCount(), is(1));
   assertThat(metaData.getColumnName(1), is("TABLE_CAT"));
   assertThat(resultSet.next(), is(true));
   assertThat(resultSet.next(), is(false));
   resultSet.close();
   connection.close();
   assertThat(connection.isClosed(), is(true));
 }
  @Test
  public void destroy_shouldCloseAllConnections() throws SQLException {
    Connection c1 = connectionPool.reserveConnection();
    Connection c2 = connectionPool.reserveConnection();
    try {
      connectionPool.destroy();
    } catch (RuntimeException e) {
      // The test connection pool throws an exception when the pool was
      // not empty but only after cleanup of the real pool has been done
    }

    Assert.assertTrue(c1.isClosed());
    Assert.assertTrue(c2.isClosed());
  }
  public void testCloseGlobalContextNoRecycle() throws Exception {
    if (log.isDebugEnabled()) {
      log.debug("*** Starting testCloseGlobalContextNoRecycle");
    }
    TransactionManager tm = TransactionManagerServices.getTransactionManager();
    tm.begin();

    Connection c1 = pds.getConnection();
    Connection c2 = pds.getConnection();
    c1.createStatement();
    c1.close();
    assertTrue(c1.isClosed());

    try {
      c1.createStatement();
      fail("expected SQLException");
    } catch (SQLException ex) {
      assertEquals("connection handle already closed", ex.getMessage());
    }

    c2.createStatement();

    try {
      c2.commit();
      fail("expected SQLException");
    } catch (SQLException ex) {
      assertEquals("cannot commit a resource enlisted in a global transaction", ex.getMessage());
    }

    tm.commit();
    assertFalse(c2.isClosed());

    c2.close();
    assertTrue(c2.isClosed());

    try {
      c2.createStatement();
      fail("expected SQLException");
    } catch (SQLException ex) {
      assertEquals("connection handle already closed", ex.getMessage());
    }

    try {
      c2.commit();
      fail("expected SQLException");
    } catch (SQLException ex) {
      assertEquals("connection handle already closed", ex.getMessage());
    }
  }
 @Ignore
 @Test
 public void testNoFactory() throws Exception {
   final Connection connection = DriverManager.getConnection("jdbc:avatica:remote:");
   assertThat(connection.isClosed(), is(false));
   final ResultSet resultSet = connection.getMetaData().getSchemas();
   assertFalse(resultSet.next());
   final ResultSetMetaData metaData = resultSet.getMetaData();
   assertEquals(2, metaData.getColumnCount());
   assertEquals("TABLE_SCHEM", metaData.getColumnName(1));
   assertEquals("TABLE_CATALOG", metaData.getColumnName(2));
   resultSet.close();
   connection.close();
   assertThat(connection.isClosed(), is(true));
 }
 @Ignore
 @Test
 public void testCatalogsMock() throws Exception {
   final Connection connection = mjs();
   assertThat(connection.isClosed(), is(false));
   final ResultSet resultSet = connection.getMetaData().getSchemas();
   assertFalse(resultSet.next());
   final ResultSetMetaData metaData = resultSet.getMetaData();
   assertEquals(2, metaData.getColumnCount());
   assertEquals("TABLE_SCHEM", metaData.getColumnName(1));
   assertEquals("TABLE_CATALOG", metaData.getColumnName(2));
   resultSet.close();
   connection.close();
   assertThat(connection.isClosed(), is(true));
 }
Beispiel #17
0
  public void insert(String[] keys, List<String> values, int[] types) throws Exception {
    try {
      if (connect.isClosed()) {
        connect =
            DriverManager.getConnection(
                "jdbc:mysql://localhost/" + database + "?" + "user=root&password=passw0rd");
      }
      if (!connect.isClosed()) {
        String insertSQL = "";
        String columns = "";
        for (int i = 0; i < keys.length; i++) {
          insertSQL += "?,";
          columns += keys[i] + ",";
        }
        insertSQL = insertSQL.substring(0, insertSQL.lastIndexOf(','));
        columns = columns.substring(0, columns.lastIndexOf(','));
        insertSQL = "insert into " + this.tableName + "(" + columns + ") values(" + insertSQL + ")";

        this.preparedStatement = this.connect.prepareStatement(insertSQL);

        for (int i = 0; i < keys.length; i++) {
          int type = types[i];
          String value = values.get(i);
          if (null == value) value = "NULL";
          if (type == 0) { // int
            preparedStatement.setInt(i + 1, new Integer(value));

          } else if (type == 1) { // timestamp
            // preparedStatement.setTimestamp(i, new Timestamp(value));

          } else if (type == 2) { // String					
            preparedStatement.setString(i + 1, value);
          }
          // preparedStatement.set
        }

        preparedStatement.executeUpdate();
        preparedStatement.close();

      } else {
        System.out.println("connection to mysql is closed");
      }

    } catch (Exception e) {
      close();
      throw e;
    }
  }
Beispiel #18
0
 /**
  * 将不再使用的连接返回给连接池
  *
  * @param con 客户程序释放的连接
  */
 public synchronized void freeConnection(Connection con) {
   // 将指定连接加入到向量末尾
   try {
     if (con.isClosed()) {
       System.out.println("before freeConnection con is closed");
     }
     freeConnections.addElement(con);
     Connection contest = (Connection) freeConnections.lastElement();
     if (contest.isClosed()) {
       System.out.println("after freeConnection contest is closed");
     }
     notifyAll();
   } catch (SQLException e) {
     System.out.println(e);
   }
 }
Beispiel #19
0
  @Test
  public void testClose() throws IOException, ClassNotFoundException, SQLException {
    // connection part
    TJDBCConnectionDefinition connectionDefinition = new TJDBCConnectionDefinition();
    TJDBCConnectionProperties connectionProperties =
        DBTestUtils.createCommonJDBCConnectionProperties(allSetting, connectionDefinition);

    JDBCSourceOrSink sourceOrSink = new JDBCSourceOrSink();
    sourceOrSink.initialize(null, connectionProperties);

    ValidationResult result = sourceOrSink.validate(container);
    assertTrue(result.getStatus() == ValidationResult.Result.OK);

    // commit part
    TJDBCCommitDefinition commitDefinition = new TJDBCCommitDefinition();
    TJDBCCommitProperties commitProperties =
        (TJDBCCommitProperties) commitDefinition.createRuntimeProperties();

    commitProperties.referencedComponent.componentInstanceId.setValue(refComponentId);
    commitProperties.closeConnection.setValue(true);

    JDBCCommitSourceOrSink commitSourceOrSink = new JDBCCommitSourceOrSink();
    commitSourceOrSink.initialize(container, commitProperties);
    commitSourceOrSink.validate(container);

    try (java.sql.Connection refConnection =
        (java.sql.Connection)
            container.getComponentData(refComponentId, ComponentConstants.CONNECTION_KEY)) {
      assertTrue(refConnection != null);
      Assert.assertTrue(refConnection.isClosed());
    }
  }
Beispiel #20
0
  public Object getDAO(String key, Connection conn) throws FactoryException {
    if (logger.isDebugEnabled()) {
      logger.debug("getDAO(String, Connection) - start");
    }

    IDAO dao = null;

    try {
      if (null != key) {
        Class cls = (Class) this.daoInstances.get(key);
        if (null != cls) {
          dao = (IDAO) ClassHelper.newInstance(cls.getName());
          if (null != conn && !conn.isClosed()) dao.setConnection(conn);
        }
      }
    } catch (Exception e) {
      logger.error("getDAO(String, Connection)", e);

      FactoryException fe = new FactoryException(e);
      throw fe;
    }
    if (null == dao) {
      FactoryException fe = new FactoryException("申请的dao没有注册到系统中�?");
      throw fe;
    }

    if (logger.isDebugEnabled()) {
      logger.debug("getDAO(String, Connection) - end");
    }
    return dao;
  }
Beispiel #21
0
 @Before
 public void init() {
   SqlSession session = MyBatisTestUtil.getSession();
   Connection c = session.getConnection();
   Statement s = null;
   try {
     s = c.createStatement();
     s.execute("TRUNCATE TABLE entity");
   } catch (SQLException e) {
     e.printStackTrace();
   } finally {
     try {
       if (s != null && !s.isClosed()) {
         s.close();
       }
       if (c != null && c.isClosed()) {
         c.close();
       }
     } catch (SQLException e) {
       e.printStackTrace();
     }
     if (session != null) {
       session.close();
     }
   }
 }
Beispiel #22
0
  public static Connection getConnection()
      throws IOException, ClassNotFoundException, SQLException, NamingException {
    if (connection == null || connection.isClosed()) {

      InputStream in =
          JDBCConnection.class.getClassLoader().getResourceAsStream("jdbc.dev.properties");
      //			InputStream in =
      // JDBCConnection.class.getClassLoader().getResourceAsStream("/MavenWebAppSample2/webapp/jdbc.dev.properties");

      //			InputStream in = null;

      if (in != null) {
        logger.info("Using jdbc.dev.properties");
        Properties prop = new Properties();
        prop.load(in);
        in.close();

        String url = prop.getProperty("url");
        String user = prop.getProperty("user");
        String pass = prop.getProperty("pass");
        String driver = prop.getProperty("driver");

        // Dev mode
        Class.forName(driver);
        connection = java.sql.DriverManager.getConnection(url, user, pass);
      } else {
        logger.info("Using data source");
        // Cloud mode
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");
        connection = ds.getConnection();
      }
    }
    return connection;
  }
 private void checkConnect() {
   try {
     if (conn == null || conn.isClosed()) connect();
   } catch (SQLException ex) {
     System.out.println(ex.getLocalizedMessage());
   }
 }
Beispiel #24
0
 public boolean isConnected() {
   try {
     return (connection != null && !connection.isClosed());
   } catch (SQLException e) {
     return false;
   }
 }
  private void btnInsertActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnInsertActionPerformed
    Connection dbConnection = null;
    PreparedStatement pstatement = null;
    String sql;
    try {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      dbConnection =
          DriverManager.getConnection(
              "jdbc:oracle:thin:@deltahiti31202:1521:XE", "Kaushal", "thullu");
      sql = "INSERT INTO EMPLOYEES(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY) VALUES (?,?,?,?)";
      pstatement = dbConnection.prepareStatement(sql);
      pstatement.setInt(1, Integer.parseInt(txtEmployeeID.getText()));
      pstatement.setString(2, txtFirstName.getText());
      pstatement.setString(3, txtLastName.getText());
      pstatement.setDouble(4, Double.parseDouble(txtSalary.getText()));
      pstatement.executeUpdate();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        if (dbConnection != null && !dbConnection.isClosed()) {
          dbConnection.close();
        }
        if (pstatement != null) {
          pstatement.close();
        }

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  } // GEN-LAST:event_btnInsertActionPerformed
  private void btnDeleteActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnDeleteActionPerformed
    Connection dbConnection = null;
    PreparedStatement pstatement = null;
    String sql;
    try {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      dbConnection =
          DriverManager.getConnection(
              "jdbc:oracle:thin:@deltahiti31202:1521:XE", "Kaushal", "thullu");
      sql = "DELETE FROM EMPLOYEES WHERE EMPLOYEE_ID=?";
      pstatement = dbConnection.prepareStatement(sql);
      pstatement.setInt(1, Integer.parseInt(txtEmployeeID.getText()));
      pstatement.executeUpdate();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        if (dbConnection != null && !dbConnection.isClosed()) {
          dbConnection.close();
        }
        if (pstatement != null) {
          pstatement.close();
        }

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  } // GEN-LAST:event_btnDeleteActionPerformed
Beispiel #27
0
  private String getMaxKey(Connection conn) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    String key = null;
    boolean reconn = false;
    try {
      if (conn == null || conn.isClosed()) {
        conn = this.dbobj.getConnection(ConnectionType.SYS);
        reconn = true;
      }
      ps = conn.prepareStatement(this.cmd.maxKey(Singleton.getInstance().getSysDBType()));

      rs = ps.executeQuery();
      if (rs.next()) {
        if (DCIString.isNullOrEmpty(rs.getString(1)) || !DCIString.isInteger(rs.getString(1))) {
          key = "1";
        } else {
          key = String.valueOf(rs.getInt(1) + 1);
        }
      } else {
        key = "1";
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      key = "";
    } finally {
      if (reconn) {
        this.dbctrl.closeConnection(rs, ps, conn);
      } else {
        this.dbctrl.closeConnection(rs, ps, null);
      }
    }
    return key;
  }
Beispiel #28
0
 public boolean isClosed() throws SQLException {
   if (bNotInUse) {
     return true;
   } else {
     return con.isClosed();
   }
 }
  @Override
  public ResultSet ExecuteSproc(String sprocName, String[] parameters, int[] returnColumnTypes)
      throws SQLException {
    if (_conn.isClosed()) {
      throw new SQLException("Connection was already closed");
    }

    try {

      String paramsList = "";

      int listSize = parameters.length;
      for (int i = 0; i < listSize; i++) {
        paramsList += parameters[i];
        if (i != listSize - 1) {
          paramsList += ", ";
        }
      }

      CallableStatement statement =
          _conn.prepareCall("{call " + sprocName + "(" + paramsList + ")}");

      for (int i = 0; i < returnColumnTypes.length; i++) {
        statement.registerOutParameter(i + 1, returnColumnTypes[i]);
      }

      return statement.executeQuery();
    } catch (SQLException ex) {
      throw ex;
    }
  }
 public void testIsClosed() throws Exception {
   for (int i = 0; i < getMaxActive(); i++) {
     Connection conn = newConnection();
     assertNotNull(conn);
     assertTrue(!conn.isClosed());
     PreparedStatement stmt = conn.prepareStatement("select * from dual");
     assertNotNull(stmt);
     ResultSet rset = stmt.executeQuery();
     assertNotNull(rset);
     assertTrue(rset.next());
     rset.close();
     stmt.close();
     conn.close();
     assertTrue(conn.isClosed());
   }
 }