Esempio n. 1
1
  private Integer executeDocInsert(JCas jCas) throws SQLException, BaleenException {
    DocumentAnnotation da = getDocumentAnnotation(jCas);
    String documentId = ConsumerUtils.getExternalId(da, contentHashAsId);

    insertDocStatement.clearParameters();
    insertDocStatement.setString(1, documentId);
    insertDocStatement.setString(2, da.getDocType());
    insertDocStatement.setString(3, da.getSourceUri());
    insertDocStatement.setString(4, jCas.getDocumentText());
    insertDocStatement.setString(5, jCas.getDocumentLanguage());
    insertDocStatement.setTimestamp(6, new Timestamp(da.getTimestamp()));
    insertDocStatement.setString(7, da.getDocumentClassification());
    insertDocStatement.setArray(
        8, createVarcharArray(postgresResource.getConnection(), da.getDocumentCaveats()));
    insertDocStatement.setArray(
        9, createVarcharArray(postgresResource.getConnection(), da.getDocumentReleasability()));
    insertDocStatement.executeUpdate();

    Integer docKey = getKey(insertDocStatement);
    if (docKey == null) {
      throw new BaleenException("No document key returned");
    }

    return docKey;
  }
  private void testPreparedSubquery(Connection conn) throws SQLException {
    Statement s = conn.createStatement();
    s.executeUpdate("CREATE TABLE TEST(ID IDENTITY, FLAG BIT)");
    s.executeUpdate("INSERT INTO TEST(ID, FLAG) VALUES(0, FALSE)");
    s.executeUpdate("INSERT INTO TEST(ID, FLAG) VALUES(1, FALSE)");
    PreparedStatement u = conn.prepareStatement("SELECT ID, FLAG FROM TEST ORDER BY ID");
    PreparedStatement p = conn.prepareStatement("UPDATE TEST SET FLAG=true WHERE ID=(SELECT ?)");
    p.clearParameters();
    p.setLong(1, 0);
    assertEquals(1, p.executeUpdate());
    p.clearParameters();
    p.setLong(1, 1);
    assertEquals(1, p.executeUpdate());
    ResultSet rs = u.executeQuery();
    assertTrue(rs.next());
    assertEquals(0, rs.getInt(1));
    assertTrue(rs.getBoolean(2));
    assertTrue(rs.next());
    assertEquals(1, rs.getInt(1));
    assertTrue(rs.getBoolean(2));

    p = conn.prepareStatement("SELECT * FROM TEST WHERE EXISTS(SELECT * FROM TEST WHERE ID=?)");
    p.setInt(1, -1);
    rs = p.executeQuery();
    assertFalse(rs.next());
    p.setInt(1, 1);
    rs = p.executeQuery();
    assertTrue(rs.next());

    s.executeUpdate("DROP TABLE IF EXISTS TEST");
  }
Esempio n. 3
0
  private void doDeleteComment(int msgid, String reason, User user, int scoreBonus)
      throws SQLException, ScriptErrorException {
    if (!getReplys(msgid).isEmpty()) {
      throw new ScriptErrorException("Нельзя удалить комментарий с ответами");
    }

    deleteComment.clearParameters();
    insertDelinfo.clearParameters();

    deleteComment.setInt(1, msgid);
    insertDelinfo.setInt(1, msgid);
    insertDelinfo.setInt(2, user.getId());
    insertDelinfo.setString(3, reason + " (" + scoreBonus + ')');

    updateScore.setInt(1, scoreBonus);
    updateScore.setInt(2, msgid);

    deleteComment.executeUpdate();
    insertDelinfo.executeUpdate();
    updateScore.executeUpdate();

    logger.info(
        "Удалено сообщение "
            + msgid
            + " пользователем "
            + user.getNick()
            + " по причине `"
            + reason
            + '\'');
  }
  public static ArrayList<StatisticalReports> retrieveStatistics(String username, String password) {

    ArrayList<StatisticalReports> allStatistics = new ArrayList<StatisticalReports>();
    DBCreation sql = DBCreation.getInstance();
    Connection conn;
    ResultSet res = null;
    PreparedStatement st;
    conn = sql.connect();
    ArrayList<String> nodes = new ArrayList<String>();
    int i;

    if (!checkMobileExistance(username, password)) {
      System.out.println("Invalid un or pw of android client");
      return null;
    }
    try {

      st = conn.prepareStatement("select clientID from clients");
      res = st.executeQuery();
      while (res.next()) {
        nodes.add(res.getString("clientID"));
      }
      st.clearParameters();

      for (i = 0; i < nodes.size(); i++) {
        StatisticalReports nodeStatistics = new StatisticalReports();

        st = conn.prepareStatement("SELECT * FROM statistics WHERE nodeID = ? ");
        st.setString(1, nodes.get(i));
        res = st.executeQuery();

        ArrayList<StatisticsEntry> statistic = new ArrayList<StatisticsEntry>();

        while (res.next()) {
          StatisticsEntry stat = new StatisticsEntry();
          stat.setNodeID(res.getString("nodeID"));
          stat.setInterfaceName(res.getString("interfaceName"));
          //	            	stat.setMaliciousPatternID(res.getInt("maliciousPatternID"));
          stat.setMaliciousPattern(getMaliciousByID(res.getInt("maliciousPatternID")));
          stat.setInterfaceIP(res.getString("interfaceIP"));
          stat.setFrequency(res.getInt("frequency"));

          statistic.add(stat);
        }
        nodeStatistics.setStatisticalReportEntries(statistic);
        allStatistics.add(nodeStatistics);
        st.clearParameters();
      }
    } catch (SQLException e) {
      e.printStackTrace();
      // System.out.println("Can't get malicious patterns from db");
    } finally {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    return allStatistics;
  }
  /**
   * <code>deleteEntry</code> deletes one entry from database.
   *
   * @param pCurrentEntry entry to delete
   * @return entry to display after deletion
   */
  @Override
  public final E deleteEntry(final String pCurrentEntry) {
    E resultValue = null;
    final AbstractDomainUser thisUser = this.getUser();
    if (thisUser != null) {
      final int mandator = thisUser.getMandator();
      final String user = thisUser.getUser();

      try {
        // connect to database
        final InitialContext ic = new InitialContext();
        final DataSource lDataSource = (DataSource) ic.lookup(this.getLookUpDataBase());
        try (final Connection thisDataBase = lDataSource.getConnection()) {

          if (this.allowedToChange()) {
            final E dbEntry = this.readEntry(pCurrentEntry);
            // invalidate head number
            if (this.getInvalidateHeadSQL() != null) {
              try (final PreparedStatement invalidateHeadSQLStatement =
                  thisDataBase.prepareStatement(this.getInvalidateHeadSQL())) {
                invalidateHeadSQLStatement.clearParameters();
                invalidateHeadSQLStatement.setInt(1, mandator);
                invalidateHeadSQLStatement.setString(2, pCurrentEntry);
                invalidateHeadSQLStatement.executeUpdate();
                this.insertEntry(thisDataBase, mandator, user, dbEntry, true);
              }
            }

            try (PreparedStatement invalidatePosSQLStatement =
                thisDataBase.prepareStatement(this.invalidatePosSQL)) {
              int numPos = 0;
              if (dbEntry.getKeyPos() != null) {
                numPos = dbEntry.getKeyPos().length;
              }
              for (int i = 0; i < numPos; i++) {
                int sqlPos = 1;
                invalidatePosSQLStatement.clearParameters();
                invalidatePosSQLStatement.setInt(sqlPos++, mandator);
                invalidatePosSQLStatement.setString(sqlPos++, pCurrentEntry);
                invalidatePosSQLStatement.setString(sqlPos++, dbEntry.getKeyPos()[i]);
                invalidatePosSQLStatement.executeUpdate();
                this.insertPositionEntry(thisDataBase, mandator, user, dbEntry, true, i);
              }
            }
          }

          resultValue = this.readNextEntry(pCurrentEntry);
        }
        ic.close();
      } catch (final SQLException e) {
        resultValue = null;
      } catch (final NamingException e) {
        resultValue = null;
      }
    }
    return resultValue;
  }
  /**
   * Verifies that the prepared statement pool behaves as an LRU cache, closing least-recently-used
   * statements idle in the pool to make room for new ones if necessary.
   */
  @Test
  public void testLRUBehavior() throws Exception {
    ds.setMaxOpenPreparedStatements(3);

    Connection conn = getConnection();
    assertNotNull(conn);

    // Open 3 statements and then close them into the pool
    PreparedStatement stmt1 = conn.prepareStatement("select 'a' from dual");
    PreparedStatement inner1 =
        (PreparedStatement) ((DelegatingPreparedStatement) stmt1).getInnermostDelegate();
    PreparedStatement stmt2 = conn.prepareStatement("select 'b' from dual");
    PreparedStatement inner2 =
        (PreparedStatement) ((DelegatingPreparedStatement) stmt2).getInnermostDelegate();
    PreparedStatement stmt3 = conn.prepareStatement("select 'c' from dual");
    PreparedStatement inner3 =
        (PreparedStatement) ((DelegatingPreparedStatement) stmt3).getInnermostDelegate();
    stmt1.close();
    Thread.sleep(100); // Make sure return timestamps are different
    stmt2.close();
    Thread.sleep(100);
    stmt3.close();

    // Pool now has three idle statements, getting another one will force oldest (stmt1) out
    PreparedStatement stmt4 = conn.prepareStatement("select 'd' from dual");
    assertNotNull(stmt4);

    // Verify that inner1 has been closed
    try {
      inner1.clearParameters();
      fail("expecting SQLExcption - statement should be closed");
    } catch (SQLException ex) {
      // Expected
    }
    // But others are still open
    inner2.clearParameters();
    inner3.clearParameters();

    // Now make sure stmt1 does not come back from the dead
    PreparedStatement stmt5 = conn.prepareStatement("select 'a' from dual");
    PreparedStatement inner5 =
        (PreparedStatement) ((DelegatingPreparedStatement) stmt5).getInnermostDelegate();
    assertNotSame(inner5, inner1);

    // inner2 should be closed now
    try {
      inner2.clearParameters();
      fail("expecting SQLExcption - statement should be closed");
    } catch (SQLException ex) {
      // Expected
    }
    // But inner3 should still be open
    inner3.clearParameters();
  }
  /** ******************* new methods U P D A T E D ******************************* */
  public static boolean register(String username, String password, AvailableNodes nodes) {
    DBCreation sql = DBCreation.getInstance();
    Connection conn = sql.connect();
    boolean registered = false;
    ResultSet res = null;

    try {

      /** ***** check if this username is already used... **** */
      String query = "select username from android_clients where username = ?";
      PreparedStatement st = conn.prepareStatement(query);
      st.setString(1, username);
      res = st.executeQuery();

      if (res.next()) {
        System.out.println("This username is  already registered");
        return registered;
      }
      st.clearParameters();

      String query_2 = " insert into android_clients (username, password)" + " values (?, ?);";
      st = conn.prepareStatement(query_2);
      st.setString(1, username);
      st.setString(2, password);
      st.executeUpdate();
      st.clearParameters();
      registered = true;

      /** ********* fill the clients table *************** */
      ListIterator<String> iteratorList = nodes.getNodes().listIterator();
      while (iteratorList.hasNext()) {
        st = conn.prepareStatement("UPDATE clients SET belongs_to_android=? WHERE clientID=? ");
        st.setString(1, username);
        st.setString(2, iteratorList.next());
        st.executeUpdate();
        st.clearParameters();
      }
    } catch (SQLException e) {
      System.out.println("Can't insert into android_clients table!");
      e.printStackTrace();
    } finally {
      try {
        conn.close();
        return registered;
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return registered;
  }
  public void execute(InputStream inputStream) throws Exception {

    this.inputStream = inputStream;

    try {

      deleteOldRecords();
      noIds = getNOIds();
      classCodesLegal = getClassCodeLegal();

      String query =
          "INSERT INTO chm62edt_habitat_class_code (ID_HABITAT, ID_CLASS_CODE, TITLE, RELATION_TYPE, CODE) VALUES (?,?,?,?,?)";

      this.preparedStatement = con.prepareStatement(query);

      String queryUpdateSitesTabInfo =
          "UPDATE chm62edt_tab_page_habitats SET LEGAL_INSTRUMENTS='Y' WHERE ID_NATURE_OBJECT = ?";

      this.preparedStatementTabInfo = con.prepareStatement(queryUpdateSitesTabInfo);

      // con.setAutoCommit(false);
      parseDocument();
      if (!(counter % 10000 == 0)) {
        preparedStatement.executeBatch();
        preparedStatement.clearParameters();

        preparedStatementTabInfo.executeBatch();
        preparedStatementTabInfo.clearParameters();
      }
      // con.commit();
    } catch (Exception e) {
      // con.rollback();
      // con.commit();
      throw new IllegalArgumentException(e.getMessage(), e);
    } finally {
      if (preparedStatement != null) {
        preparedStatement.close();
      }

      if (preparedStatementTabInfo != null) {
        preparedStatementTabInfo.close();
      }

      if (con != null) {
        con.close();
      }
    }
  }
  public int countPending(Connection connection) {

    PreparedStatement pst = null;
    ResultSet rst = null;
    try {

      pst =
          connection.prepareStatement(
              "select count(*) from " //$NON-NLS-1$
                  + SEARCH_BUILDER_ITEM_T
                  + " where searchstate = ? "); //$NON-NLS-1$
      pst.clearParameters();
      pst.setInt(1, SearchBuilderItem.STATE_PENDING.intValue());
      rst = pst.executeQuery();
      if (rst.next()) {
        return rst.getInt(1);
      }
      return 0;
    } catch (SQLException sqlex) {
      return 0;
    } finally {
      try {
        rst.close();
      } catch (Exception ex) {
        log.debug(ex);
      }
      try {
        pst.close();
      } catch (Exception ex) {
        log.debug(ex);
      }
    }
  }
  public static void deleteMaliciousPattern(int patternID) {
    DBCreation sql = DBCreation.getInstance();
    Connection conn;
    PreparedStatement st;
    conn = sql.connect();
    try {

      st = conn.prepareStatement("DELETE FROM statistics WHERE maliciousPatternID=?");
      st.setInt(1, patternID);
      st.executeUpdate();
      st.clearParameters();

      st = conn.prepareStatement("DELETE FROM maliciousPatterns WHERE patternID=?");
      st.setInt(1, patternID);
      st.executeUpdate();

      gui.ReportTerminalOperations.addReport(
          "> DELETE FROM maliciousPatterns WHERE patternID='" + patternID + "'");

    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
Esempio n. 11
0
  public void dataCountStore() {
    Connection con = null;
    int listId;

    try {
      con = L2DatabaseFactory.getInstance().getConnection();
      PreparedStatement statement =
          con.prepareStatement(
              "UPDATE merchant_buylists SET currentCount=? WHERE item_id=? AND shop_id=?");
      for (L2TradeList list : _lists.values()) {
        if (list.hasLimitedStockItem()) {
          listId = list.getListId();

          for (L2TradeItem item : list.getItems()) {
            long currentCount;
            if (item.hasLimitedStock()
                && (currentCount = item.getCurrentCount()) < item.getMaxCount()) {
              statement.setLong(1, currentCount);
              statement.setInt(2, item.getItemId());
              statement.setInt(3, listId);
              statement.executeUpdate();
              statement.clearParameters();
            }
          }
        }
      }
      statement.close();
    } catch (Exception e) {
      _log.log(Level.SEVERE, "TradeController: Could not store Count Item: " + e.getMessage(), e);
    } finally {
      L2DatabaseFactory.close(con);
    }
  }
 protected void addUserAuthorizations(
     String username, List<Authorization> authorizations, Connection conn) {
   PreparedStatement stat = null;
   try {
     stat = conn.prepareStatement(ADD_AUTHORIZATION);
     for (int i = 0; i < authorizations.size(); i++) {
       Authorization auth = authorizations.get(i);
       if (null == auth) continue;
       stat.setString(1, username);
       if (null != auth.getGroup()) {
         stat.setString(2, auth.getGroup().getName());
       } else {
         stat.setNull(2, Types.VARCHAR);
       }
       if (null != auth.getRole()) {
         stat.setString(3, auth.getRole().getName());
       } else {
         stat.setNull(3, Types.VARCHAR);
       }
       stat.addBatch();
       stat.clearParameters();
     }
     stat.executeBatch();
   } catch (Throwable t) {
     _logger.error("Error detected while addind user authorizations", t);
     throw new RuntimeException("Error detected while addind user authorizations", t);
   } finally {
     this.closeDaoResources(null, stat);
   }
 }
Esempio n. 13
0
  /**
   *
   *
   * <pre>
   * ���� �߰�
   * # 20091017 �����ƺ� CUBRID�� ���̱׷��̼� �ϸ鼭 ������ �ڵ��� ������� �ٲ�
   * </pre>
   *
   * @param conn
   * @param seq
   * @param arrdf
   * @throws SQLException
   */
  public void addFile(Connection conn, int seq, ArrayList<DownFile> arrdf) throws SQLException {
    // file �Ϸù�ȣ
    int fseq = fetchNew(conn, QUERY_NEW_FILE_SEQ);

    // file �Է�
    PreparedStatement pstmt = null;
    try {
      pstmt = conn.prepareStatement(QUERY_ADD_FILE);
      DownFile df;
      for (int i = 0; i < arrdf.size(); i++) {
        df = arrdf.get(i);
        if (df.getFileSize() > 0) {
          pstmt.clearParameters();

          pstmt.setInt(1, fseq);
          pstmt.setInt(2, seq);
          pstmt.setString(3, df.getFileName());
          pstmt.setString(4, df.getMaskName());
          pstmt.setLong(5, df.getFileSize());

          pstmt.executeUpdate();
          fseq++;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      dbCon.close(null, pstmt);
    }
  }
Esempio n. 14
0
  public static void saveZutaten(Rezept r, Connection con) throws SQLException {
    Set set = r.zutaten.keySet();
    Iterator iter = set.iterator();

    PreparedStatement stmt = null;

    try {
      String sql = "delete from zut2rez where rez_id = ?";
      stmt = con.prepareStatement(sql);
      stmt.setLong(1, r.getId());
      stmt.execute();
      stmt.close();

      sql = "insert into zut2rez(zut_id, rez_id, menge) values(?,?,?)";
      stmt = con.prepareStatement(sql);

      while (iter.hasNext()) {
        Long id = (Long) iter.next();
        Long wert = r.zutaten.get(id);
        stmt.setLong(1, id);
        stmt.setLong(2, r.getId());
        stmt.setLong(3, wert);
        stmt.execute();
        stmt.clearParameters();
      }
    } finally {
      DbUtil.close(stmt);
    }
  }
 private List getSiteMasterItems(Connection connection) throws SQLException {
   PreparedStatement pst = null;
   ResultSet rst = null;
   try {
     pst =
         connection.prepareStatement(
             "select " //$NON-NLS-1$
                 + SEARCH_BUILDER_ITEM_FIELDS
                 + " from " //$NON-NLS-1$
                 + SEARCH_BUILDER_ITEM_T
                 + " where itemscope =   ?  "); //$NON-NLS-1$
     pst.clearParameters();
     pst.setInt(1, SearchBuilderItem.ITEM_SITE_MASTER.intValue());
     rst = pst.executeQuery();
     ArrayList<SearchBuilderItemImpl> a = new ArrayList<SearchBuilderItemImpl>();
     while (rst.next()) {
       SearchBuilderItemImpl sbi = new SearchBuilderItemImpl();
       populateSearchBuilderItem(rst, sbi);
       a.add(sbi);
     }
     return a;
   } finally {
     try {
       rst.close();
     } catch (Exception ex) {
       log.debug(ex);
     }
     try {
       pst.close();
     } catch (Exception ex) {
       log.debug(ex);
     }
   }
 }
Esempio n. 16
0
 private void processHeros(PreparedStatement ps, int charId, StatsSet hero) throws SQLException {
   ps.setInt(1, charId);
   try (ResultSet rs = ps.executeQuery()) {
     if (rs.next()) {
       int clanId = rs.getInt("clanid");
       int allyId = rs.getInt("allyId");
       String clanName = "";
       String allyName = "";
       int clanCrest = 0;
       int allyCrest = 0;
       if (clanId > 0) {
         clanName = ClanTable.getInstance().getClan(clanId).getName();
         clanCrest = ClanTable.getInstance().getClan(clanId).getCrestId();
         if (allyId > 0) {
           allyName = ClanTable.getInstance().getClan(clanId).getAllyName();
           allyCrest = ClanTable.getInstance().getClan(clanId).getAllyCrestId();
         }
       }
       hero.set(CLAN_CREST, clanCrest);
       hero.set(CLAN_NAME, clanName);
       hero.set(ALLY_CREST, allyCrest);
       hero.set(ALLY_NAME, allyName);
     }
     ps.clearParameters();
   }
 }
Esempio n. 17
0
  /** @throws SQLException */
  static void fillPath(String path, String name, PreparedStatement prep) throws SQLException {

    File f = new File(path);

    if (f.isFile()) {

      // Clear all Parameters of the PreparedStatement
      prep.clearParameters();

      // Fill the first parameter: Path
      prep.setString(1, path);

      // Fill the second parameter: Name
      prep.setString(2, name);

      // Its a file: add it to the table
      prep.execute();
    } else if (f.isDirectory()) {
      if (!path.endsWith(File.separator)) {
        path += File.separator;
      }

      String[] list = f.list();

      // Process all files recursivly
      for (int i = 0; (list != null) && (i < list.length); i++) {
        fillPath(path + list[i], list[i], prep);
      }
    }
  }
  @Test
  public void testSetters() throws Exception {
    BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
    tm.setTransactionTimeout(30);
    tm.begin();

    Connection connection = poolingDataSource1.getConnection();

    long start = System.nanoTime();
    PreparedStatement stmt =
        connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?");
    Date date = new Date(0);
    for (int i = 0; i < 50000; i++) {
      stmt.setString(1, "foo");
      stmt.setInt(2, 999);
      stmt.setDate(3, date);
      stmt.setFloat(4, 9.99f);
      stmt.clearParameters();
    }
    long totalTime = System.nanoTime() - start;

    stmt.executeQuery();

    connection.close();

    tm.commit();
    tm.shutdown();
  }
Esempio n. 19
0
  public ResultSet addRecord(final ProductEntry record) throws SQLException {
    stmtSaveNewRecord.clearParameters();
    int i = 1;
    if (record.getFile() == null) stmtSaveNewRecord.setString(i++, "");
    else stmtSaveNewRecord.setString(i++, record.getFile().getAbsolutePath());
    stmtSaveNewRecord.setString(i++, record.getName());
    stmtSaveNewRecord.setString(i++, record.getMission());
    stmtSaveNewRecord.setString(i++, record.getProductType());
    stmtSaveNewRecord.setString(i++, record.getAcquisitionMode());
    stmtSaveNewRecord.setString(i++, record.getPass());
    stmtSaveNewRecord.setDouble(i++, record.getFirstNearGeoPos().getLat());
    stmtSaveNewRecord.setDouble(i++, record.getFirstNearGeoPos().getLon());
    stmtSaveNewRecord.setDouble(i++, record.getFirstFarGeoPos().getLat());
    stmtSaveNewRecord.setDouble(i++, record.getFirstFarGeoPos().getLon());
    stmtSaveNewRecord.setDouble(i++, record.getLastNearGeoPos().getLat());
    stmtSaveNewRecord.setDouble(i++, record.getLastNearGeoPos().getLon());
    stmtSaveNewRecord.setDouble(i++, record.getLastFarGeoPos().getLat());
    stmtSaveNewRecord.setDouble(i++, record.getLastFarGeoPos().getLon());
    stmtSaveNewRecord.setDouble(i++, record.getRangeSpacing());
    stmtSaveNewRecord.setDouble(i++, record.getAzimuthSpacing());
    stmtSaveNewRecord.setDate(i++, SQLUtils.toSQLDate(record.getFirstLineTime()));
    stmtSaveNewRecord.setDouble(i++, record.getFileSize());
    stmtSaveNewRecord.setDouble(i++, record.getLastModified());
    stmtSaveNewRecord.setString(i++, record.getFileFormat());
    final String geoStr = record.formatGeoBoundayString();
    if (geoStr.length() > 1200) {
      System.out.println("Geoboundary string exceeds 1200");
      stmtSaveNewRecord.setString(i++, "");
    } else {
      stmtSaveNewRecord.setString(i++, geoStr);
    }

    final int rowCount = stmtSaveNewRecord.executeUpdate();
    return stmtSaveNewRecord.getGeneratedKeys();
  }
Esempio n. 20
0
 public boolean pathExists(final File path) throws SQLException {
   if (path == null) return false;
   stmtGetProductWithPath.clearParameters();
   stmtGetProductWithPath.setString(1, path.getAbsolutePath());
   final ResultSet results = stmtGetProductWithPath.executeQuery();
   return results.next();
 }
Esempio n. 21
0
  public void closePoolableStatement(DruidPooledPreparedStatement stmt) throws SQLException {
    PreparedStatement rawStatement = stmt.getRawPreparedStatement();

    if (holder == null) {
      return;
    }

    if (stmt.isPooled()) {
      try {
        rawStatement.clearParameters();
      } catch (SQLException ex) {
        this.handleException(ex);
        if (rawStatement.getConnection().isClosed()) {
          return;
        }

        LOG.error("clear parameter error", ex);
      }
    }

    stmt.getPreparedStatementHolder().decrementInUseCount();
    if (stmt.isPooled() && holder.isPoolPreparedStatements()) {
      holder.getStatementPool().put(stmt.getPreparedStatementHolder());

      stmt.clearResultSet();
      holder.removeTrace(stmt);

      stmt.getPreparedStatementHolder().setFetchRowPeak(stmt.getFetchRowPeak());

      stmt.setClosed(true); // soft set close
    } else {
      stmt.closeInternal();
      holder.getDataSource().incrementClosedPreparedStatementCount();
    }
  }
Esempio n. 22
0
  public void insertAgenda(String nome_paciente, int telefone) {

    if (nome_paciente == null) {
      throw new IllegalArgumentException("O nome do paciente não pode ser null.");
    }

    try {
      Connection con =
          DriverManager.getConnection(
              "jdbc:postgresql://localhost:5432/consultorio", "postgres", "senacrs");

      PreparedStatement stmt = con.prepareStatement(insertAgenda);
      stmt.clearParameters();
      stmt.setString(1, nome_paciente);
      stmt.setInt(2, telefone);
      int in = stmt.executeUpdate();
      if (in != 1) {
        throw new RuntimeException("Erro ao inserir operação");
      }
    } catch (Exception e) {
      // FIXME: comunicar erro ao programa
      e.printStackTrace();
    }
    // FIXME: fechar conexões
  }
  // get and show the values of the actual row in the GUI
  private void showAktRow() {

    try {
      pStmt.clearParameters();

      for (int i = 0; i < primaryKeys.length; i++) {
        pStmt.setObject(i + 1, resultRowPKs[aktRowNr][i]);
      } // end of for (int i=0; i<primaryKeys.length; i++)

      ResultSet rs = pStmt.executeQuery();

      rs.next();

      for (int i = 0; i < columns.length; i++) {
        komponente[i].setContent(rs.getString(i + 1));
      } // end of for (int i=0; i<primaryKeys.length; i++)

      rs.close();
    } catch (SQLException e) {
      ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
    } // end of try-catch

    for (int i = 0; i < columns.length; i++) {
      komponente[i].clearChanges();
    }
  }
  public PublicacaoBean recuperaPublicacoes(int id) throws SSDAOException {
    PublicacaoBean objPublicacao = new PublicacaoBean();
    PreparedStatement ps = null;
    Connection conn = null;
    String SQL = "";
    try {

      SQL = "SELECT * FROM PUBLICATION  " + "WHERE ID=?";

      conn = this.conn;
      ps = conn.prepareStatement(SQL);
      ps.clearParameters();
      ps.setInt(1, id);
      ResultSet rs = ps.executeQuery();

      while (rs.next()) {
        objPublicacao.setID(rs.getInt("ID"));
        objPublicacao.setTitulo(rs.getString("TITLE"));
        objPublicacao.setLocal(rs.getString("BOOKTITLE"));
        objPublicacao.setAno(rs.getInt("YEAR"));
        objPublicacao.setAutor(retornaAutores(objPublicacao.getID()));
        objPublicacao.setPaginas(retornaPaginas(objPublicacao.getID()));
      }

    } catch (SQLException e) {
      throw new SSDAOException("Erro ao consultar dados " + e);
    } finally {
      ConnectionSSFactory.closeConnection(conn, ps);
    }
    return objPublicacao;
  }
Esempio n. 25
0
  public void transaction_search(int cid, String movie_title) throws Exception {
    /* searches for movies with matching titles: SELECT * FROM movie WHERE name LIKE movie_title */
    /* prints the movies, directors, actors, and the availability status:
    AVAILABLE, or UNAVAILABLE, or YOU CURRENTLY RENT IT */

    /* Interpolate the movie title into the SQL string */
    String searchSql = SEARCH_SQL_BEGIN + movie_title + SEARCH_SQL_END;

    Statement searchStatement = conn.createStatement();
    ResultSet movie_set = searchStatement.executeQuery(searchSql);
    while (movie_set.next()) {
      int mid = movie_set.getInt(1);
      System.out.println(
          "ID: " + mid + " NAME: " + movie_set.getString(2) + " YEAR: " + movie_set.getString(3));
      /* do a dependent join with directors */
      directorMidStatement.clearParameters();
      directorMidStatement.setInt(1, mid);
      ResultSet director_set = directorMidStatement.executeQuery();
      while (director_set.next()) {
        System.out.println(
            "\t\tDirector: " + director_set.getString(3) + " " + director_set.getString(2));
      }
      director_set.close();
      /* now you need to retrieve the actors, in the same manner */
      /* then you have to find the status: of "AVAILABLE" "YOU HAVE IT", "UNAVAILABLE" */
    }
    movie_set.close();
    System.out.println();
  }
  private String[] retornaAutores(int ID) throws SSDAOException {
    int nAutores = retornaNAutores(ID);
    String[] autores = new String[nAutores];
    PreparedStatement ps = null;
    Connection conn = null;
    String SQL = "";
    int cont = 0;
    try {
      SQL = "SELECT * FROM ID_AUTHOR WHERE ID=?";
      conn = this.conn;
      ps = conn.prepareStatement(SQL);
      ps.clearParameters();
      ps.setInt(1, ID);
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        autores[cont] = rs.getString("AUTHOR");
        cont++;
      }

    } catch (SQLException e) {
      throw new SSDAOException("Erro ao consultar dados " + e);
    }

    return autores;
  }
  private boolean verificarExistencia(int n, String p, int par) throws SSDAOException {
    PreparedStatement ps = null;
    String SQL = "";
    int cont = 0;
    try {
      if (n == TBIDAUTHOR) {
        SQL = "SELECT * FROM ID_AUTHOR WHERE AUTHOR=? AND ID=?";
      }
      ps = conn.prepareStatement(SQL);
      ps.clearParameters();
      ps.setString(1, p);
      ps.setInt(2, par);
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        cont++;
      }

    } catch (SQLException e) {
      throw new SSDAOException("Erro ao inserir dados " + e);
    } finally {
      if (cont == 0) {
        return false;
      } else {
        return true;
      }
    }
  }
Esempio n. 28
0
 private void executeDocMetadataInsert(Integer docKey, Metadata md) throws SQLException {
   insertDocMetadataStatement.clearParameters();
   insertDocMetadataStatement.setInt(1, docKey);
   insertDocMetadataStatement.setString(2, md.getKey());
   insertDocMetadataStatement.setString(3, md.getValue());
   insertDocMetadataStatement.executeUpdate();
 }
 public void clearParameters() throws SQLException {
   checkOpen();
   try {
     _stmt.clearParameters();
   } catch (SQLException e) {
     handleException(e);
   }
 }
 public void clearParameters() throws SQLException {
   try {
     this.memento.clear();
     wrapped.clearParameters();
   } catch (SQLException e) {
     throw new UcanaccessSQLException(e);
   }
 }