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));
    }
  }
Exemplo n.º 2
0
  public void cadastrarPessoa() {
    Statement statement = Conexao.conectar();
    if ((fieldNome.getText() != null && !fieldNome.getText().equals(""))
        && (fieldRG.getText() != null && !fieldRG.getText().equals(""))) {
      String sql =
          "insert into dbe_paciente(nome, rg) values('"
              + fieldNome.getText()
              + "', '"
              + fieldRG.getText()
              + "');";

      try {
        statement.executeUpdate(sql);
        JOptionPane.showMessageDialog(
            null,
            "Paciente Cadastrado com Sucesso!!! ",
            "Sucesso",
            JOptionPane.INFORMATION_MESSAGE);
        Conexao.desconectar(statement.getConnection());
        statement.close();
        janela.dispose();
      } catch (SQLException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
      }
    } else {
      JOptionPane.showMessageDialog(
          null, "Preencha Nome e RG", "Erro", JOptionPane.WARNING_MESSAGE);
    }
  }
Exemplo n.º 3
0
 private boolean moveToNextResultsSafely(StatementScope scope, Statement stmt)
     throws SQLException {
   if (forceMultipleResultSetSupport(scope)
       || stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
     return stmt.getMoreResults();
   }
   return false;
 }
Exemplo n.º 4
0
 protected void safeClose(Statement stmt) {
   if (stmt != null) {
     try {
       safeClose(stmt.getConnection());
       stmt.close();
     } catch (SQLException e) {
     }
   }
 }
Exemplo n.º 5
0
  /** {@inheritDoc} */
  @Override
  protected void afterTest() throws Exception {
    if (stmt != null) {
      stmt.getConnection().close();
      stmt.close();

      assert stmt.isClosed();
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.talend.dataprofiler.core.sampling.SamplingDataSource#finalizeDataSampling()
   */
  public boolean finalizeDataSampling() throws Exception {
    if (jdbcResultSet != null) {
      Statement statement = jdbcResultSet.getStatement();
      Connection connection = statement.getConnection();

      jdbcResultSet.close();
      statement.close();
      connection.close();
    }
    return true;
  }
Exemplo n.º 7
0
 /**
  * Fill the PARENT column of the DIRECTORIES table with correct values. Used when upgrading a
  * database from an old format that doesn't have the PARENT column.
  */
 private static void fillDirectoriesParentColumn(Statement s) throws SQLException {
   try (PreparedStatement update =
           s.getConnection().prepareStatement(getQuery("updateDirectoriesParent"));
       ResultSet rs = s.executeQuery(getQuery("getAllDirectories"))) {
     while (rs.next()) {
       update.setInt(1, rs.getInt("REPOSITORY"));
       update.setString(2, getParentPath(rs.getString("PATH")));
       update.setInt(3, rs.getInt("ID"));
       update.executeUpdate();
     }
   }
 }
Exemplo n.º 8
0
  /**
   * Create java code to add function copy paste into GeoSpatialFunctionsAddRemove to upload it
   *
   * @param st SQL Statement
   * @param function Function instance
   * @param packagePrepend For OSGi environment only, use Bundle-SymbolicName:Bundle-Version:
   * @param dropAlias Drop alias if exists before define it.
   */
  public static void registerFunction(
      Statement st, Function function, String packagePrepend, boolean dropAlias)
      throws SQLException {
    String functionClass = function.getClass().getName();
    String functionAlias = getAlias(function);

    if (function instanceof ScalarFunction) {
      ScalarFunction scalarFunction = (ScalarFunction) function;
      String functionName = scalarFunction.getJavaStaticMethod();
      if (dropAlias) {
        st.execute("DROP ALIAS IF EXISTS " + functionAlias);
      }
      String deterministic = "";
      if (getBooleanProperty(function, ScalarFunction.PROP_DETERMINISTIC, false)) {
        deterministic = " DETERMINISTIC";
      }
      String nobuffer = "";
      if (getBooleanProperty(function, ScalarFunction.PROP_NOBUFFER, false)) {
        nobuffer = " NOBUFFER";
      }
      // Create alias, H2 does not support prepare statement on create alias
      st.execute(
          "CREATE ALIAS IF NOT EXISTS "
              + functionAlias
              + deterministic
              + nobuffer
              + " FOR \""
              + packagePrepend
              + functionClass
              + "."
              + functionName
              + "\"");
      // Set comment
      String functionRemarks = getStringProperty(function, Function.PROP_REMARKS);
      if (!functionRemarks.isEmpty()) {
        PreparedStatement ps =
            st.getConnection().prepareStatement("COMMENT ON ALIAS " + functionAlias + " IS ?");
        ps.setString(1, functionRemarks);
        ps.execute();
      }
    } else if (function instanceof Aggregate) {
      st.execute(
          "CREATE AGGREGATE IF NOT EXISTS "
              + functionAlias
              + " FOR \""
              + packagePrepend
              + functionClass
              + "\"");
    } else {
      throw new SQLException("Unsupported function " + functionClass);
    }
  }
Exemplo n.º 9
0
  private void parseInstancesForTable(Element table, ArrayList<Element> attributes) {
    String tableName = table.getName();
    String attributeList = null;
    for (int i = 0; i < attributes.size(); i++) {
      Element element = attributes.get(i);
      String attributeName = element.getName();
      if (i == 0) {
        attributeList = attributeName;
      } else {
        attributeList += ", " + attributeName;
      }
    }
    String url = null;
    try {
      url = statement.getConnection().getMetaData().getURL();
      if (url != null && url.contains(":")) {
        url = url.substring(url.lastIndexOf(":") + 1);
      }
    } catch (SQLException e1) {
    }

    String query = "SELECT " + attributeList + " FROM ";
    try {

      if (attributeList != null && attributeList.contains("table")) {
        if (url != null) {
          query = "SELECT * FROM " + url + "." + tableName;
        } else {
          query = "SELECT * FROM " + tableName;
        }
      } else if (url != null) {
        query += url + "." + tableName;
      } else {
        query += tableName;
      }
      ResultSet rs = statement.executeQuery(query);
      int connect = 1;
      while (rs.next() && connect < Repository.INSTANCES_MAX_PER_ELEMENT) {
        String connectString = connect + "";
        for (int i = 0; i < attributes.size(); i++) {
          Element element = attributes.get(i);
          String value = rs.getString(element.getName());
          saveInstanceToRepository(element, value, connectString, importer);
        }
        connect++;
      }
    } catch (SQLException e) {

      System.out.println("parseInstancesForTable(): " + e.getMessage());
      System.out.println(query);
    }
  }
Exemplo n.º 10
0
 public void releaseStatement(Statement statement) throws SQLException {
   if (statement == null) return;
   Connection conn = null;
   try {
     conn = statement.getConnection();
     statement.close();
     releaseConnection(conn);
   } catch (SQLException e) {
     log4j.error("releaseStatement: " + e);
     releaseConnection(conn);
     throw e;
   }
 }
Exemplo n.º 11
0
 private ResultSetWrapper getNextResultSet(Statement stmt) throws SQLException {
   // Making this method tolerant of bad JDBC drivers
   try {
     if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
       // Crazy Standard JDBC way of determining if there are more results
       if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) {
         ResultSet rs = stmt.getResultSet();
         return rs != null ? new ResultSetWrapper(rs, configuration) : null;
       }
     }
   } catch (Exception e) {
     // Intentionally ignored.
   }
   return null;
 }
Exemplo n.º 12
0
  private void initDB(Statement s) throws SQLException {
    // TODO Store a database version which is incremented on each
    // format change. When a version change is detected, drop the database
    // or, if possible, upgrade the database to the new format. For now,
    // check if the tables exist, and create them if necessary.

    DatabaseMetaData dmd = s.getConnection().getMetaData();

    if (!tableExists(dmd, SCHEMA, "REPOSITORIES")) {
      s.execute(getQuery("createTableRepositories"));
    }

    if (!tableExists(dmd, SCHEMA, "DIRECTORIES")) {
      s.execute(getQuery("createTableDirectories"));
    }

    // Databases created with 0.11 or earlier versions don't have a
    // PARENT column in the DIRECTORIES table. If the column is missing,
    // create it and populate it. Bug #3174.
    if (!columnExists(dmd, SCHEMA, "DIRECTORIES", "PARENT")) {
      s.execute(getQuery("alterTableDirectoriesParent"));
      s.execute(getQuery("alterTableDirectoriesParentPathConstraint"));
      fillDirectoriesParentColumn(s);
    }

    if (!tableExists(dmd, SCHEMA, "FILES")) {
      s.execute(getQuery("createTableFiles"));
    }

    if (!tableExists(dmd, SCHEMA, "AUTHORS")) {
      s.execute(getQuery("createTableAuthors"));
    }

    if (!tableExists(dmd, SCHEMA, "CHANGESETS")) {
      s.execute(getQuery("createTableChangesets"));
      // Create a composite index on the repository in ascending order
      // and the id in descending order. This index may allow faster
      // retrieval of history in reverse chronological order.
      s.execute(getQuery("createIndexChangesetsRepoIdDesc"));
    }

    if (!tableExists(dmd, SCHEMA, "DIRCHANGES")) {
      s.execute(getQuery("createTableDirchanges"));
    }

    if (!tableExists(dmd, SCHEMA, "FILECHANGES")) {
      s.execute(getQuery("createTableFilechanges"));
    }

    if (!tableExists(dmd, SCHEMA, "FILEMOVES")) {
      s.execute(getQuery("createTableFilemoves"));
    }

    // Derby has some performance problems with auto-generated identity
    // columns when multiple threads insert into the same table
    // concurrently. Therefore, we have our own light-weight id generators
    // that we initialize on start-up. Details can be found in Derby's
    // bug tracker: https://issues.apache.org/jira/browse/DERBY-4437

    initIdGenerator(s, "getMaxFileId", nextFileId);
    initIdGenerator(s, "getMaxDirId", nextDirId);
    initIdGenerator(s, "getMaxChangesetId", nextChangesetId);
    initIdGenerator(s, "getMaxAuthorId", nextAuthorId);

    StringBuilder infoBuilder = new StringBuilder();
    infoBuilder.append(getClass().getSimpleName() + "\n");
    infoBuilder.append("Driver class: " + jdbcDriverClass + "\n");
    infoBuilder.append("URL: " + jdbcConnectionURL + "\n");
    infoBuilder.append("Database name: " + dmd.getDatabaseProductName() + "\n");
    infoBuilder.append("Database version: " + dmd.getDatabaseProductVersion() + "\n");
    info = infoBuilder.toString();
  }
 public void test_createStatement() throws Exception {
   Connection con = DriverManager.getConnection("jdbc:fakeDriver");
   Statement stmt = con.createStatement();
   assertEquals(stmt.getConnection(), con);
 }
Exemplo n.º 14
0
  private void testCompareWithPostgreSQL() throws Exception {
    ArrayList<Statement> statements = New.arrayList();
    ArrayList<Transaction> transactions = New.arrayList();
    ArrayList<TransactionMap<Integer, String>> maps = New.arrayList();
    int connectionCount = 3, opCount = 1000, rowCount = 10;
    try {
      Class.forName("org.postgresql.Driver");
      for (int i = 0; i < connectionCount; i++) {
        Connection conn = DriverManager.getConnection("jdbc:postgresql:test", "sa", "sa");
        statements.add(conn.createStatement());
      }
    } catch (Exception e) {
      // database not installed - ok
      return;
    }
    statements.get(0).execute("drop table if exists test cascade");
    statements.get(0).execute("create table test(id int primary key, name varchar(255))");

    MVStore s = MVStore.open(null);
    TransactionStore ts = new TransactionStore(s);
    for (int i = 0; i < connectionCount; i++) {
      Statement stat = statements.get(i);
      // 100 ms to avoid blocking (the test is single threaded)
      stat.execute("set statement_timeout to 100");
      Connection c = stat.getConnection();
      c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
      c.setAutoCommit(false);
      Transaction transaction = ts.begin();
      transactions.add(transaction);
      TransactionMap<Integer, String> map;
      map = transaction.openMap("test");
      maps.add(map);
    }
    StringBuilder buff = new StringBuilder();

    Random r = new Random(1);
    try {
      for (int i = 0; i < opCount; i++) {
        int connIndex = r.nextInt(connectionCount);
        Statement stat = statements.get(connIndex);
        Transaction transaction = transactions.get(connIndex);
        TransactionMap<Integer, String> map = maps.get(connIndex);
        if (transaction == null) {
          transaction = ts.begin();
          map = transaction.openMap("test");
          transactions.set(connIndex, transaction);
          maps.set(connIndex, map);

          // read all data, to get a snapshot
          ResultSet rs = stat.executeQuery("select * from test order by id");
          buff.append(i).append(": [" + connIndex + "]=");
          int size = 0;
          while (rs.next()) {
            buff.append(' ');
            int k = rs.getInt(1);
            String v = rs.getString(2);
            buff.append(k).append(':').append(v);
            assertEquals(v, map.get(k));
            size++;
          }
          buff.append('\n');
          if (size != map.sizeAsLong()) {
            assertEquals(size, map.sizeAsLong());
          }
        }
        int x = r.nextInt(rowCount);
        int y = r.nextInt(rowCount);
        buff.append(i).append(": [" + connIndex + "]: ");
        ResultSet rs = null;
        switch (r.nextInt(7)) {
          case 0:
            buff.append("commit");
            stat.getConnection().commit();
            transaction.commit();
            transactions.set(connIndex, null);
            break;
          case 1:
            buff.append("rollback");
            stat.getConnection().rollback();
            transaction.rollback();
            transactions.set(connIndex, null);
            break;
          case 2:
            // insert or update
            String old = map.get(x);
            if (old == null) {
              buff.append("insert " + x + "=" + y);
              if (map.tryPut(x, "" + y)) {
                stat.execute("insert into test values(" + x + ", '" + y + "')");
              } else {
                buff.append(" -> row was locked");
                // the statement would time out in PostgreSQL
                // TODO test sometimes if timeout occurs
              }
            } else {
              buff.append("update " + x + "=" + y + " (old:" + old + ")");
              if (map.tryPut(x, "" + y)) {
                int c = stat.executeUpdate("update test set name = '" + y + "' where id = " + x);
                assertEquals(1, c);
              } else {
                buff.append(" -> row was locked");
                // the statement would time out in PostgreSQL
                // TODO test sometimes if timeout occurs
              }
            }
            break;
          case 3:
            buff.append("delete " + x);
            try {
              int c = stat.executeUpdate("delete from test where id = " + x);
              if (c == 1) {
                map.remove(x);
              } else {
                assertNull(map.get(x));
              }
            } catch (SQLException e) {
              assertTrue(map.get(x) != null);
              assertFalse(map.tryRemove(x));
              // PostgreSQL needs to rollback
              buff.append(" -> rollback");
              stat.getConnection().rollback();
              transaction.rollback();
              transactions.set(connIndex, null);
            }
            break;
          case 4:
          case 5:
          case 6:
            rs = stat.executeQuery("select * from test where id = " + x);
            String expected = rs.next() ? rs.getString(2) : null;
            buff.append("select " + x + "=" + expected);
            assertEquals("i:" + i, expected, map.get(x));
            break;
        }
        buff.append('\n');
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(buff.toString());
    }
    for (Statement stat : statements) {
      stat.getConnection().close();
    }
    ts.close();
    s.close();
  }
Exemplo n.º 15
0
  @Override
  public int read(java.lang.Object pk, java.sql.Statement statement) {
    int[] key = (int[]) pk;
    String sql = "";
    ResultSet resultSet = null;
    Statement statementAux = null;

    mnLastDbActionResult = SLibConstants.UNDEFINED;
    reset();

    try {
      sql = "SELECT * FROM erp.finu_tax_bas WHERE id_tax_bas = " + key[0] + " ";
      resultSet = statement.executeQuery(sql);
      if (!resultSet.next()) {
        throw new Exception(SLibConstants.MSG_ERR_REG_FOUND_NOT);
      } else {
        mnPkTaxBasicId = resultSet.getInt("id_tax_bas");
        msTaxBasic = resultSet.getString("tax_bas");
        mbIsDeleted = resultSet.getBoolean("b_del");
        mnFkUserNewId = resultSet.getInt("fid_usr_new");
        mnFkUserEditId = resultSet.getInt("fid_usr_edit");
        mnFkUserDeleteId = resultSet.getInt("fid_usr_del");
        mtUserNewTs = resultSet.getTimestamp("ts_new");
        mtUserEditTs = resultSet.getTimestamp("ts_edit");
        mtUserDeleteTs = resultSet.getTimestamp("ts_del");

        statementAux = statement.getConnection().createStatement();

        // Read aswell the taxes

        sql =
            "SELECT id_tax_bas, id_tax FROM erp.finu_tax WHERE id_tax_bas = "
                + key[0]
                + " "
                + "ORDER BY tax, id_tax_bas, id_tax ";
        resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
          SDataTax tax = new SDataTax();
          if (tax.read(
                  new int[] {resultSet.getInt("id_tax_bas"), resultSet.getInt("id_tax")},
                  statementAux)
              != SLibConstants.DB_ACTION_READ_OK) {
            throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP);
          } else {
            mvDbmsTaxes.add(tax);
          }
        }

        mbIsRegistryNew = false;
        mnLastDbActionResult = SLibConstants.DB_ACTION_READ_OK;
      }
    } catch (java.sql.SQLException e) {
      mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR;
      SLibUtilities.printOutException(this, e);
    } catch (java.lang.Exception e) {
      mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR;
      SLibUtilities.printOutException(this, e);
    }

    return mnLastDbActionResult;
  }