Gets the next seed from the database for this sequence.
@param conn the database connection
@throws java.sql.SQLException a database error occurred
500538
private void reseed(Connection conn) throws SQLException {
        logger.debug("enter - reseed()");
        try {
            PreparedStatement stmt = null;
            ResultSet rs = null;
            
            try {
                // Keep in this loop as long as we encounter concurrency errors
                do {
                    stmt = conn.prepareStatement(FIND_SEQ);
                    stmt.setString(SEL_NAME, getName());
                    rs = stmt.executeQuery();
                    if( !rs.next() ) {
                        logger.info("No sequence in DB for " + getName() + ".");
                        // no such sequence, create it
                        {
                            // close resources
                            try { rs.close(); }
                            catch( SQLException ignore ) { /* ignore */ }
                            rs = null;
                            try { stmt.close(); }
                            catch( SQLException ignore ) { /* ignore */ }
                            stmt = null;
                        }
                        sequence = 100L;
                        nextKey = sequence + interval;
                        create(conn);
                    }
                    else {
                        long ts;
                        
                        sequence = rs.getLong(SEL_NEXT_KEY);
                        interval = rs.getLong(SEL_INTERVAL);
                        if( interval < 1 ) {
                            interval = defaultInterval;
                        }
                        nextKey = sequence + interval;
                        ts = rs.getLong(SEL_UPDATE);
                        {
                            // close resources
                            try { rs.close(); }
                            catch( SQLException ignore ) { /* ignore */ }
                            rs = null;
                            try { stmt.close(); }
                            catch( SQLException ignore ) { /* ignore */ }
                            stmt = null;
                        }
                        // increment the seed in the database
                        stmt = conn.prepareStatement(UPDATE_SEQ);
                        stmt.setLong(UPD_NEXT_KEY, nextKey);
                        stmt.setLong(UPD_SET_UPDATE, System.currentTimeMillis());
                        stmt.setString(UPD_NAME, getName());
                        stmt.setLong(UPD_WHERE_KEY, sequence);
                        stmt.setLong(UPD_WHERE_UPDATE, ts);
                        if( stmt.executeUpdate() != 1 ) {
                            // someone changed the database! try again!
                            sequence = -1L;
                            logger.warn("Concurrency error, requerying DB.");
                        }
                        else {
                            if( !conn.getAutoCommit() ) {
                                conn.commit();
                            }
                        }
                    }
                } while( sequence == -1L );
                logger.info("Sequence set to " + sequence + ", next_key is " +
                            nextKey + ".");
            }
            finally {
                if( rs != null ) {
                    try { rs.close(); }
                    catch( SQLException ignore ) { /* ignore */ }
                }
                if( stmt != null ) {
                    try { stmt.close(); }
                    catch( SQLException ignore ) { /* ignore */ }
                }
            }   
        }
        finally {
            logger.debug("exit - reseed()");
        }
    }
813979
public synchronized Connection getConnection() throws DatabaseException {
        initialize();
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(connectionString, userName, password);
        } catch (SQLException ex) {
            LOGGER.debug("", ex);
            throw new DatabaseException("Unable to connect to the database", ex);
        }
        return conn;
    }
1286643
private int getTotalCount(String sql, Connection conn, MappedStatement ms, BoundSql boundSql) throws SQLException {
    int start = sql.indexOf("from");
    if (start == -1) {
      throw new RuntimeException("statement has no 'from' keyword");
    }
    int stop = sql.indexOf("order by");
    if (stop == -1) {
      stop = sql.length();
    }

    String countSql = "select count(0) " + sql.substring(start, stop);
    BoundSql countBoundSql = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    ParameterHandler parameterHandler = new DefaultParameterHandler(ms, boundSql.getParameterObject(), countBoundSql);
    PreparedStatement stmt = null;
    ResultSet rs = null;
    int count = 0;
    try {
      stmt = conn.prepareStatement(countSql);
      // 通过parameterHandler给PreparedStatement对象设置参数
      parameterHandler.setParameters(stmt);
      rs = stmt.executeQuery();
      if (rs.next()) {
        count = rs.getInt(1);
      }
    } finally {
      CloseableUtil.closeQuietly(rs);
      CloseableUtil.closeQuietly(stmt);
    }
    return count;
  }
478155
protected long buildNextSequence(PersistenceBroker broker, ClassDescriptor cld, String sequenceName)
            throws LookupException, SQLException, PlatformException
    {
        CallableStatement cs = null;
        try
        {
            Connection con = broker.serviceConnectionManager().getConnection();
            cs = getPlatform().prepareNextValProcedureStatement(con, PROCEDURE_NAME, sequenceName);
            cs.executeUpdate();
            return cs.getLong(1);
        }
        finally
        {
            try
            {
                if (cs != null)
                    cs.close();
            }
            catch (SQLException ignore)
            {
                // ignore it
            }
        }
    }
62970
public boolean tableExists (Connection conn, String name) throws SQLException
    {
        ResultSet rs = conn.getMetaData().getTables(null, null, name, null);
        while (rs.next()) {
            String tname = rs.getString("TABLE_NAME");
            if (name.equals(tname)) {
                return true;
            }
        }
        return false;
    }
795100
protected function _getSearchResults( MW_DB_Connection_Interface $conn, $sql )
	{
		$context = $this->_getContext();
		$statement = $conn->create( $sql );

		try {
			$statement->bind( 1, $context->getLocale()->getSiteId(), MW_DB_Statement_Abstract::PARAM_INT );
		} catch( Exception $e ) {
			$statement->bind( 1, null, MW_DB_Statement_Abstract::PARAM_INT );
		}

		return $statement->execute();
	}
1041549
@Override
	public T next() {
		SQLException sqlException = null;
		try {
			T result = nextThrow();
			if (result != null) {
				return result;
			}
		} catch (SQLException e) {
			sqlException = e;
		}
		// we have to throw if there is no next or on a SQLException
		last = null;
		closeQuietly();
		throw new IllegalStateException("Could not get next result for " + dataClass, sqlException);
	}
1014902
@Override
    protected void reconnect(Connection conn) throws DatabaseException {
        try {
			if (!DbUtils.hasTable(conn, TABLE_NAME)) {
			    // Need to create the table
			    DbUtils.execute(
			            conn, "CREATE cached TABLE STRUCTURE (STRUCTUREID bigint generated by default as identity (start with 1), " +
			            		"SESSIONID bigint not null, PARENTID bigint not null, HISTORYID int, " +
			            		"NAME varchar(8192) not null, NAMEHASH bigint not null, " +
			            		"URL varchar(8192) not null, METHOD varchar(10) not null)");
			}

			psRead	= conn.prepareStatement("SELECT * FROM STRUCTURE WHERE SESSIONID = ? AND STRUCTUREID = ?");

			psFind	= conn.prepareStatement("SELECT * FROM STRUCTURE WHERE SESSIONID = ? AND NAMEHASH = ? AND METHOD = ?");

			psInsert = conn.prepareStatement("INSERT INTO STRUCTURE (SESSIONID, PARENTID, HISTORYID, NAME, NAMEHASH, URL, METHOD) VALUES (?, ?, ?, ?, ?, ?, ?)");
			psGetIdLastInsert = conn.prepareCall("CALL IDENTITY();");

			psGetChildren = conn.prepareStatement("SELECT * FROM STRUCTURE WHERE SESSIONID = ? AND PARENTID = ?");

			psGetChildCount = conn.prepareStatement("SELECT COUNT(*) FROM STRUCTURE WHERE SESSIONID = ? AND PARENTID = ?");

		} catch (SQLException e) {
			throw new DatabaseException(e);
		}
    }
1351971
public int[] insert(Connection conn, Entity... records) throws SQLException {
		checkConn(conn);
		if(ArrayUtil.isEmpty(records)){
			return new int[]{0};
		}
		
		//单条单独处理
		if(1 == records.length) {
			return new int[] { insert(conn, records[0])};
		}
		
		PreparedStatement ps = null;
		try {
			ps = dialect.psForInsertBatch(conn, records);
			return ps.executeBatch();
		} finally {
			DbUtil.close(ps);
		}
	}
366065
private synchronized void open(Execution event, String dsn) throws SQLException, PersistenceException {
        try {
            Connection conn;
            
            if( connection != null ) {
                return;
            }
            state = "OPENING";
            try {
                InitialContext ctx = new InitialContext();
                DataSource ds;
                
                if( dsn == null ) {
                    dsn = event.getDataSource();
                }
                if (dsn == null) {
                    throw new PersistenceException("No data source name");
                }
                state = "LOOKING UP";
                ds = dsCache.get(dsn);
                if (ds == null) {
                    ds = (DataSource)ctx.lookup(dsn);
                    if (ds != null) {
                        dsCache.put(dsn, ds);
                    }
                }
                if (ds == null) {
                    throw new PersistenceException("Could not find data source: " + dsn);
                }
                conn = ds.getConnection();
                openTime = System.currentTimeMillis();
                if( logger.isDebugEnabled() ) {
                    logger.debug("DPTRANSID-" + transactionId + " connection.get - dsn='" + dsn + '\'');
                }
                state = "CONNECTED";
            }
            catch( NamingException e ) {
                logger.error("Problem with datasource: " + e.getMessage());
                throw new PersistenceException(e.getMessage());
            }
            conn.setAutoCommit(false);
            conn.setReadOnly(readOnly);
            connection = conn;
            if (tracking) {
                connections.incrementAndGet();
                transactions.put(new Integer(transactionId), this);
            }
        }
        finally {
        }
    }
141184
public synchronized Connection getConnection() throws SQLException {
        if ((currentTimeMillis() - lastChecked)
        > VALIDITY_CHECK_INTERVAL) {
            logger.trace("Checking connection validity");
            // check the validity of the connection
            boolean valid = false;
            int t = 0;

            while (!valid && t < REATTEMPTS) {
                try {
                    if (connection == null || connection.isClosed()
                            || !connection.isValid(VALIDITY_TIMEOUT)) {
                        logger.info(
                                "Connection to {} is closed or invalid; attempting to re-establish",
                                url);
                        // remove any cached prepared statements for this connection
                        threadedPsMap.remove();

                        // attempt re-establishment
                        this.connection = DriverManager
                                .getConnection(url, user, pass);
                        logger.info("Re-established connection to {}", url);
                        // do not set valid to true - check this new connection
                    } else {
                        valid = true;
                    }
                } catch (SQLException e) {
                    logger.info("Failed to re-establish connection to " +
                            "{}, try {}/{}; Reason: {}",
                            new Object[] { url, t, REATTEMPTS, e.getMessage() });
                    // set connection to null to prevent the same error from continuously
                    // occurring when checking isClosed() or isValid()
                    this.connection = null;
                }
                t++;
            }
            if (!valid) {
                logger.error(
                        "Failed to re-establish a connection to {} after {} attempts",
                        url, REATTEMPTS);
                throw new SQLException(
                        "Unable to re-establish a valid connection",
                        new DBConnectionFailure(url,
                                "Unable to re-establish a valid connection"));
            }
            this.lastChecked = currentTimeMillis();
        }
        return connection;
    }
861422
public final void closeConnection(final Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
827197
@Override
    public Sequence<T> next() {
        Sequence<T> sequence = new Sequence<>();
        int[] visitedHops = new int[walkLength];
        Arrays.fill(visitedHops, -1);

        int startPosition = position.getAndIncrement();
        int lastId = -1;
        int startPoint = order[startPosition];
        startPosition = startPoint;
        for (int i = 0; i < walkLength; i++) {

            Vertex<T> vertex = sourceGraph.getVertex(startPosition);

            int currentPosition = startPosition;

            sequence.addElement(vertex.getValue());
            visitedHops[i] = vertex.vertexID();
            int cSpread = 0;

            if (alpha > 0 && lastId != startPoint && lastId != -1 && alpha > rng.nextDouble()) {
                startPosition = startPoint;
                continue;
            }

            switch (walkDirection) {
                case RANDOM:
                case FORWARD_ONLY:
                case FORWARD_UNIQUE:
                case FORWARD_PREFERRED: {

                    // ArrayUtils.removeElements(sourceGraph.getConnectedVertexIndices(order[currentPosition]), visitedHops);
                    int[] connections = ArrayUtils.removeElements(
                                    sourceGraph.getConnectedVertexIndices(vertex.vertexID()), visitedHops);

                    // we get  popularity of each node connected to the current node.
                    PriorityQueue<Node<T>> queue = new PriorityQueue<>(Math.max(10, connections.length), new NodeComparator());

                    int start = 0;
                    int stop = 0;
                    int cnt = 0;
                    if (connections.length > 0) {


                        for (int connected : connections) {
                            Node<T> tNode = new Node<>(connected, sourceGraph.getConnectedVertices(connected).size());
                            queue.add(tNode);
                        }


                        cSpread = spread > connections.length ? connections.length : spread;

                        switch (popularityMode) {
                            case MAXIMUM:
                                start = 0;
                                stop = start + cSpread - 1;
                                break;
                            case MINIMUM:
                                start = connections.length - cSpread;
                                stop = connections.length - 1;
                                break;
                            case AVERAGE:
                                int mid = connections.length / 2;
                                start = mid - (cSpread / 2);
                                stop = mid + (cSpread / 2);
                                break;
                        }

                        // logger.info("Spread: ["+ cSpread+ "], Connections: ["+ connections.length+"], Start: ["+start+"], Stop: ["+stop+"]");
                        cnt = 0;
                        //logger.info("Queue: " + queue);
                        //logger.info("Queue size: " + queue.size());

                        List<Node<T>> list = new ArrayList<>();
                        double[] weights = new double[cSpread];

                        int fcnt = 0;
                        while (!queue.isEmpty()) {
                            Node<T> node = queue.poll();
                            if (cnt >= start && cnt <= stop) {
                                list.add(node);
                                weights[fcnt] = node.getWeight();
                                fcnt++;
                            }
                            connections[cnt] = node.getVertexId();

                            cnt++;
                        }


                        int con = -1;

                        switch (spectrum) {
                            case PLAIN: {
                                con = RandomUtils.nextInt(start, stop + 1);

                                //    logger.info("Picked selection: " + con);

                                Vertex<T> nV = sourceGraph.getVertex(connections[con]);
                                startPosition = nV.vertexID();
                                lastId = vertex.vertexID();
                            }
                                break;
                            case PROPORTIONAL: {
                                double norm[] = MathArrays.normalizeArray(weights, 1);
                                double prob = rng.nextDouble();
                                double floor = 0.0;
                                for (int b = 0; b < weights.length; b++) {
                                    if (prob >= floor && prob < floor + norm[b]) {
                                        startPosition = list.get(b).getVertexId();
                                        lastId = startPosition;
                                        break;
                                    } else {
                                        floor += norm[b];
                                    }
                                }
                            }
                                break;
                        }

                    } else {
                        switch (noEdgeHandling) {
                            case EXCEPTION_ON_DISCONNECTED:
                                throw new NoEdgesException("No more edges at vertex [" + currentPosition + "]");
                            case CUTOFF_ON_DISCONNECTED:
                                i += walkLength;
                                break;
                            case SELF_LOOP_ON_DISCONNECTED:
                                startPosition = currentPosition;
                                break;
                            case RESTART_ON_DISCONNECTED:
                                startPosition = startPoint;
                                break;
                            default:
                                throw new UnsupportedOperationException(
                                                "Unsupported noEdgeHandling: [" + noEdgeHandling + "]");
                        }
                    }
                }
                    break;
                default:
                    throw new UnsupportedOperationException("Unknown WalkDirection: [" + walkDirection + "]");
            }

        }

        return sequence;
    }
749624
protected DaoResult update(Connection conn, T bo) {
        if (bo == null) {
            return new DaoResult(DaoOperationStatus.NOT_FOUND);
        }
        Savepoint savepoint = null;
        try {
            try {
                String[] bindColumns = ArrayUtils.addAll(rowMapper.getUpdateColumns(),
                        rowMapper.getPrimaryKeyColumns());
                String colChecksum = rowMapper.getChecksumColumn();
                if (!StringUtils.isBlank(colChecksum)) {
                    bindColumns = ArrayUtils.add(bindColumns, colChecksum);
                }
                savepoint = conn.getAutoCommit() ? null : conn.setSavepoint();
                int numRows = execute(conn, calcSqlUpdateOne(bo),
                        rowMapper.valuesForColumns(bo, bindColumns));
                DaoResult result = numRows > 0 ? new DaoResult(DaoOperationStatus.SUCCESSFUL, bo)
                        : new DaoResult(DaoOperationStatus.NOT_FOUND);
                if (numRows > 0) {
                    invalidateCache(bo, CacheInvalidationReason.UPDATE);
                }
                return result;
            } catch (DuplicatedValueException dke) {
                if (savepoint != null) {
                    conn.rollback(savepoint);
                }
                return new DaoResult(DaoOperationStatus.DUPLICATED_VALUE);
            }
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }
495528
public void deleteGenerator (Connection conn, String table, String column)
        throws SQLException
    {
        executeQuery(conn, "drop sequence if exists \"" + table + "_" + column + "_seq\"");
    }
768942
public void createGenerator (Connection conn, String tableName, String columnName, int initValue)
        throws SQLException
    {
        if (initValue == 1) {
            return; // that's the default! yay, do nothing
        }

        String seqname = "\"" + tableName + "_" + columnName + "_seq\"";
        Statement stmt = conn.createStatement();
        try {
            stmt.executeQuery("select setval('" + seqname + "', " + initValue + ", false)");
        } finally {
            JDBCUtil.close(stmt);
        }
        log("Initial value of " + seqname  + " set to " + initValue + ".");
    }
1304347
public int insert(Connection conn, Entity record) throws SQLException {
		checkConn(conn);
		if(CollectionUtil.isEmpty(record)){
			throw new SQLException("Empty entity provided!");
		}
		PreparedStatement ps = null;
		try {
			ps = dialect.psForInsert(conn, record);
			return ps.executeUpdate();
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}