Example usage for java.sql Statement RETURN_GENERATED_KEYS

List of usage examples for java.sql Statement RETURN_GENERATED_KEYS

Introduction

In this page you can find the example usage for java.sql Statement RETURN_GENERATED_KEYS.

Prototype

int RETURN_GENERATED_KEYS

To view the source code for java.sql Statement RETURN_GENERATED_KEYS.

Click Source Link

Document

The constant indicating that generated keys should be made available for retrieval.

Usage

From source file:edu.ku.brc.specify.config.init.DataBuilder.java

/**
 * @param filename//from www . ja  v a2  s .c o m
 * @param prefix
 * @param groupMap
 */
public static void mergeDefaultPermissions(final String filename, final String prefix,
        final Map<String, List<Integer>> groupMap) {
    Hashtable<String, Hashtable<String, PermissionOptionPersist>> mainHash = BaseTask
            .readDefaultPermsFromXML(filename);
    for (String permName : mainHash.keySet()) {
        String userType = "LimitedAccess";
        Hashtable<String, PermissionOptionPersist> hash = mainHash.get(permName);
        if (hash.get(userType) == null) {
            PermissionOptionPersist permOpts = hash.get("Manager");
            PermissionOptionPersist newPermOpts = new PermissionOptionPersist(permOpts.getTaskName(), userType,
                    permOpts.isCanView(), permOpts.isCanModify(), permOpts.isCanDel(), permOpts.isCanAdd());
            hash.put(userType, newPermOpts);
        }

        userType = "FullAccess";
        hash = mainHash.get(permName);
        if (hash.get(userType) == null) {
            PermissionOptionPersist permOpts = hash.get("Manager");
            PermissionOptionPersist newPermOpts = new PermissionOptionPersist(permOpts.getTaskName(), userType,
                    permOpts.isCanView(), permOpts.isCanModify(), permOpts.isCanDel(), permOpts.isCanAdd());
            hash.put(userType, newPermOpts);
        }
    }

    /*if (additionalSecOpts != null)
    {
    for (SpecifyUserTypes.UserType userType : SpecifyUserTypes.UserType.values())
    {
        System.out.println(userType.toString()+" --------------------------------------");
        for (SecurityOptionIFace aso : additionalSecOpts)
        {
            PermissionIFace asoPerm = aso.getDefaultPermissions(userType.toString());
            if (asoPerm != null)
            {
                System.out.println("  "+prefix+aso.getPermissionName()+"  "+asoPerm.getOptions());
            }
        }
    }
    }*/

    HashMap<SpPermission, List<Integer>> prinPermHash = new HashMap<SpPermission, List<Integer>>();
    for (String permName : mainHash.keySet()) {
        String fullPermName = prefix + permName;

        Hashtable<String, PermissionOptionPersist> hash = mainHash.get(permName);
        for (String userType : hash.keySet()) {
            PermissionOptionPersist tp = hash.get(userType);
            SpPermission perm = tp.getSpPermission();

            for (Integer id : groupMap.get(userType)) {
                String str = "SELECT p.SpPermissionID FROM sppermission AS p Inner Join spprincipal_sppermission AS pp ON p.SpPermissionID = pp.SpPermissionID "
                        + "WHERE p.Name = '%s' AND pp.SpPrincipalID = %d";
                String sql = String.format(str, fullPermName, id);
                Integer permId = BasicSQLUtils.getCount(sql);
                if (permId == null) {
                    System.out.println(String.format("Going to create %s for Prin: %d", fullPermName, id));
                    List<Integer> list = prinPermHash.get(perm);
                    if (list == null) {
                        perm.setName(fullPermName);
                        list = new ArrayList<Integer>();
                        prinPermHash.put(perm, list);
                    }
                    list.add(id);
                }
            }
        }
    }

    if (prinPermHash.size() > 0) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            conn = DatabaseService.getInstance().getConnection();
            pstmt1 = conn.prepareStatement(
                    "INSERT INTO sppermission (Actions, Name, PermissionClass) VALUES (?, ?, ?)", //$NON-NLS-1$
                    Statement.RETURN_GENERATED_KEYS);
            pstmt2 = conn.prepareStatement(
                    "INSERT INTO spprincipal_sppermission (SpPermissionID, SpPrincipalID) VALUES (?, ?)"); //$NON-NLS-1$
            for (SpPermission spPerm : prinPermHash.keySet()) {
                for (Integer prinId : prinPermHash.get(spPerm)) {
                    pstmt1.setString(1, spPerm.getActions());
                    pstmt1.setString(2, spPerm.getName());
                    pstmt1.setString(3, spPerm.getClass().getName());
                    pstmt1.setString(3, BasicSpPermission.class.getCanonicalName());
                    pstmt1.executeUpdate();

                    Integer newPermId = BasicSQLUtils.getInsertedId(pstmt1);
                    pstmt2.setInt(1, newPermId);
                    pstmt2.setInt(2, prinId);
                    pstmt2.executeUpdate();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(PermissionService.class, e);
        } finally {
            try {
                if (pstmt1 != null)
                    pstmt1.close();
                if (pstmt2 != null)
                    pstmt2.close();
                if (conn != null)
                    conn.close();

            } catch (SQLException e) {
                e.printStackTrace();
                edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(PermissionService.class, e);
            }
        }
    }
}

From source file:uk.ac.ebi.sail.server.data.DataManager.java

public ClassifierShadow updateClassifier(ClassifierShadow scl) throws ClassifierManagementException {
    int id = scl.getId();
    Classifier orig = classifiers.get(id);

    if (orig == null)
        throw new ClassifierManagementException("Classifier doesn't exist ID=" + id,
                ClassifierManagementException.INV_CLASSIFIER_ID);

    SetComparator<Tag> res = SetComparator.compare(orig.getTags(), scl.getTags());

    Connection conn = null;/*w w w. j a va2 s .com*/
    ResultSet rst = null;

    try {
        conn = dSrc.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(updateClassifierSQL);

        pstmt.setString(1, scl.getName());
        pstmt.setString(2, scl.getDesc());
        pstmt.setBoolean(3, scl.isAllowMulty());
        pstmt.setBoolean(4, scl.isMandatory());
        pstmt.setString(5, scl.getTarget().name());
        pstmt.setInt(6, id);

        pstmt.executeUpdate();
        pstmt.close();

        if (res.getItemsToDelete() != null) {
            pstmt = conn.prepareStatement(deleteTagSQL);

            PreparedStatement delParamTag = conn.prepareStatement(
                    "DELETE FROM " + TBL_PARAMETER_CLASSIFICATION + " WHERE " + FLD_TAG_ID + "=?");
            PreparedStatement delClsTag = conn.prepareStatement(
                    "DELETE FROM " + TBL_CLASSIFIER_CLASSIFICATION + " WHERE " + FLD_TAG_ID + "=?");
            PreparedStatement delRelTag = conn
                    .prepareStatement("DELETE FROM " + TBL_RELATION + " WHERE " + FLD_TAG_ID + "=?");
            PreparedStatement delRepAnntTag = conn.prepareStatement(
                    "DELETE FROM " + TBL_COLLECTION_ANNOTATION + " WHERE " + FLD_TAG_ID + "=?");

            PreparedStatement delParamAnntTag = conn.prepareStatement(
                    "DELETE FROM " + TBL_PARAMETER_ANNOTATION + " WHERE " + FLD_TAG_ID + "=?");

            for (Tag t : res.getItemsToDelete()) {
                pstmt.setInt(1, t.getId());
                pstmt.executeUpdate();

                delParamTag.setInt(1, t.getId());
                delParamTag.executeUpdate();

                delClsTag.setInt(1, t.getId());
                delClsTag.executeUpdate();

                delRelTag.setInt(1, t.getId());
                delRelTag.executeUpdate();

                delRepAnntTag.setInt(1, t.getId());
                delRepAnntTag.executeUpdate();

                delParamAnntTag.setInt(1, t.getId());
                delParamAnntTag.executeUpdate();

                tags.remove(t.getId());
            }

            delParamTag.close();
            delClsTag.close();
            delRelTag.close();
            delRepAnntTag.close();
            pstmt.close();
        }

        if (res.getNewItems() != null) {
            pstmt = conn.prepareStatement(insertTagSQL, Statement.RETURN_GENERATED_KEYS);

            for (Tag t : res.getNewItems()) {
                pstmt.setString(1, t.getName());
                pstmt.setString(2, t.getDescription());
                pstmt.setInt(3, id);

                pstmt.executeUpdate();

                rst = pstmt.getGeneratedKeys();
                if (rst.next())
                    t.setId(rst.getInt(1));

                rst.close();

                tags.put(t.getId(), t);
            }

            pstmt.close();
        }

        if (res.getUpdateItems() != null && res.getUpdateItems().size() > 0) {
            pstmt = conn.prepareStatement(updateTagSQL);

            for (Tag t : res.getUpdateItems()) {
                pstmt.setString(1, t.getName());
                pstmt.setString(2, t.getDescription());
                pstmt.setInt(3, t.getId());

                pstmt.executeUpdate();
            }

            pstmt.close();
        }

        pstmt = conn.prepareStatement(deleteAllClassifierClassificationSQL);
        pstmt.setInt(1, id);
        pstmt.executeUpdate();
        pstmt.close();

        if (scl.getClassificationTags() != null) // TODO check tag existance
        {
            pstmt = conn.prepareStatement(insertClassifierClassificationSQL);

            for (int tid : scl.getClassificationTags()) {
                pstmt.setInt(1, id);
                pstmt.setInt(2, tid);

                pstmt.executeUpdate();
            }
        }

        if (res.getItemsToDelete() != null)
            updateStructure();
        else {
            orig.setName(scl.getName());
            orig.setDescription(scl.getDesc());

            if (orig.getTags() != null) {
                for (Tag ot : orig.getTags()) {
                    for (Tag nt : scl.getTags()) {
                        if (ot.getId() == nt.getId()) {
                            ot.setName(nt.getName());
                            ot.setDescription(nt.getDescription());
                            break;
                        }
                    }
                }
            }

            if (res.getNewItems() != null) {
                for (Tag t : res.getNewItems())
                    orig.addTag(t);
            }

            orig.setClassificationTags(null);
            if (scl.getClassificationTags() != null) {
                for (int tid : scl.getClassificationTags()) {
                    Tag t = tags.get(tid);

                    if (t == null) {
                        logger.warn("Invalid tag ID=" + tid);
                    } else
                        orig.addTag(t);
                }
            }

        }

        return scl;
    } catch (SQLException e) {
        logger.error("SQL error", e);
    } finally {
        if (rst != null) {
            try {
                rst.close();
            } catch (SQLException e) {

            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Log.error("Connection closing error", e);
                }
            }
        }
    }
    return null;
}

From source file:org.ut.biolab.medsavant.server.serverapi.VariantManager.java

@Override
public int replyToUserCommentGroup(String sessID, int userCommentGroupId, UserComment userComment)
        throws SessionExpiredException, SQLException, RemoteException, SecurityException {
    if (!isAuthorizedForUserComments(sessID)) {
        throw new SecurityException("This user does not have access to view comments");
    }//from  www. j  a  v  a 2 s . com

    String username = SessionManager.getInstance().getUserForSession(sessID);
    String ontologyId = userComment.getOntologyTerm().getID();

    //TODO: Insert checks here to make sure user has permissions to change flags.      
    //If they don't, use the flags in 'lastComment' commented out above.       
    Boolean isApproved = userComment.isApproved();
    Boolean isIncluded = userComment.isIncluded();
    Boolean isDeleted = userComment.isDeleted();
    String commentText = userComment.getCommentText();
    String ontology = userComment.getOntologyTerm().getOntology().name();
    TableSchema lcTable = MedSavantDatabase.UserCommentTableSchema;
    InsertQuery iq = new InsertQuery(lcTable.getTable());

    iq.addColumn(
            MedSavantDatabase.UserCommentTableSchema
                    .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_USER_COMMENT_GROUP_ID),
            userCommentGroupId);
    iq.addColumn(MedSavantDatabase.UserCommentTableSchema
            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_ONTOLOGY_ID), ontologyId);
    iq.addColumn(MedSavantDatabase.UserCommentTableSchema
            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_ONTOLOGY), ontology);
    iq.addColumn(MedSavantDatabase.UserCommentTableSchema
            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_USER), username);
    iq.addColumn(MedSavantDatabase.UserCommentTableSchema
            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_APPROVED), isApproved);
    iq.addColumn(MedSavantDatabase.UserCommentTableSchema
            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_INCLUDE), isIncluded);
    iq.addColumn(MedSavantDatabase.UserCommentTableSchema
            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_DELETED), isDeleted);
    iq.addColumn(
            MedSavantDatabase.UserCommentTableSchema
                    .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_CREATION_DATE),
            (new FunctionCall(new CustomSql("NOW"))).addCustomParams());
    iq.addColumn(MedSavantDatabase.UserCommentTableSchema
            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_COMMENT), commentText);
    if (userComment.getOriginalComment() != null) {
        Integer commentId = userComment.getOriginalComment().getCommentID();
        if (commentId == null) {
            throw new IllegalArgumentException(
                    "Cannot post this comment as it refers to a comment with a null identifier");
        }
        if (commentId < 1) {
            throw new IllegalArgumentException(
                    "Cannot post this comment as it refers to a comment with a non-positive identifier: "
                            + commentId);
        }
        iq.addColumn(
                MedSavantDatabase.UserCommentTableSchema.getDBColumn(
                        MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_PARENT_USER_COMMENT_ID),
                commentId);
    }

    PreparedStatement stmt = null;
    PooledConnection conn = ConnectionController.connectPooled(sessID);
    ResultSet res = null;
    int commentId = -1; //Not returned for now.
    try {
        stmt = conn.prepareStatement(iq.toString(), Statement.RETURN_GENERATED_KEYS);
        stmt.execute();
        res = stmt.getGeneratedKeys();
        res.next();
        commentId = res.getInt(1);
        //LOG.info("Inserted new comment with id " + commentId + " for comment group with id " + userCommentGroupId);

        //update original comment's status if necessary.
        if (userComment.getOriginalComment() != null) {
            UpdateQuery uq = new UpdateQuery(lcTable.getTable());
            uq.addCondition(BinaryCondition.equalTo(
                    MedSavantDatabase.UserCommentTableSchema.getDBColumn(
                            MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_USER_COMMENT_ID),
                    userComment.getOriginalComment().getCommentID()));
            uq.addSetClause(
                    MedSavantDatabase.UserCommentTableSchema
                            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_APPROVED),
                    userComment.getOriginalComment().isApproved());
            uq.addSetClause(
                    MedSavantDatabase.UserCommentTableSchema
                            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_INCLUDE),
                    userComment.getOriginalComment().isIncluded());
            uq.addSetClause(
                    MedSavantDatabase.UserCommentTableSchema
                            .getDBColumn(MedSavantDatabase.UserCommentTableSchema.COLUMNNAME_OF_DELETED),
                    userComment.getOriginalComment().isDeleted());
            stmt = conn.prepareStatement(uq.toString());
            stmt.execute();
        }
        return commentId;
    } catch (SQLException sqe) {
        LOG.error("SQL Error", sqe);
        throw sqe;
    } finally {
        if (conn != null) {
            conn.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (res != null) {
            res.close();
        }
    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *///www .  j ava 2s  .c  om
public void insertTopicVersions(List<TopicVersion> topicVersions, Connection conn) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    boolean useBatch = (topicVersions.size() > 1);
    try {
        if (!this.autoIncrementPrimaryKeys()) {
            stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION);
        } else if (useBatch) {
            // generated keys don't work in batch mode
            stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION_AUTO_INCREMENT);
        } else {
            stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION_AUTO_INCREMENT,
                    Statement.RETURN_GENERATED_KEYS);
        }
        int topicVersionId = -1;
        if (!this.autoIncrementPrimaryKeys() || useBatch) {
            // manually retrieve next topic version id when using batch
            // mode or when the database doesn't support generated keys.
            topicVersionId = this.nextTopicVersionId(conn);
        }
        for (TopicVersion topicVersion : topicVersions) {
            if (!this.autoIncrementPrimaryKeys() || useBatch) {
                // FIXME - if two threads update the database simultaneously then
                // it is possible that this code could set the topic version ID
                // to a value that is different from what the database ends up
                // using.
                topicVersion.setTopicVersionId(topicVersionId++);
            }
            this.prepareTopicVersionStatement(topicVersion, stmt);
            if (useBatch) {
                stmt.addBatch();
            } else {
                stmt.executeUpdate();
            }
            if (this.autoIncrementPrimaryKeys() && !useBatch) {
                rs = stmt.getGeneratedKeys();
                if (!rs.next()) {
                    throw new SQLException("Unable to determine auto-generated ID for database record");
                }
                topicVersion.setTopicVersionId(rs.getInt(1));
            }
        }
        if (useBatch) {
            stmt.executeBatch();
        }
    } finally {
        // close only the statement and result set - leave the connection open for further use
        DatabaseConnection.closeConnection(null, stmt, rs);
        stmt = null;
        rs = null;
    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *///  ww w .  j  a va  2s  .  c  o  m
public void insertUserBlock(UserBlock userBlock, Connection conn) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        int index = 1;
        if (!this.autoIncrementPrimaryKeys()) {
            stmt = conn.prepareStatement(STATEMENT_INSERT_USER_BLOCK);
            int blockId = this.nextUserBlockId(conn);
            userBlock.setBlockId(blockId);
            stmt.setInt(index++, userBlock.getBlockId());
        } else {
            stmt = conn.prepareStatement(STATEMENT_INSERT_USER_BLOCK_AUTO_INCREMENT,
                    Statement.RETURN_GENERATED_KEYS);
        }
        if (userBlock.getWikiUserId() == null) {
            stmt.setNull(index++, Types.INTEGER);
        } else {
            stmt.setInt(index++, userBlock.getWikiUserId());
        }
        stmt.setString(index++, userBlock.getIpAddress());
        stmt.setTimestamp(index++, userBlock.getBlockDate());
        stmt.setTimestamp(index++, userBlock.getBlockEndDate());
        stmt.setString(index++, userBlock.getBlockReason());
        stmt.setInt(index++, userBlock.getBlockedByUserId());
        stmt.setTimestamp(index++, userBlock.getUnblockDate());
        stmt.setString(index++, userBlock.getUnblockReason());
        if (userBlock.getUnblockedByUserId() == null) {
            stmt.setNull(index++, Types.INTEGER);
        } else {
            stmt.setInt(index++, userBlock.getUnblockedByUserId());
        }
        stmt.executeUpdate();
        if (this.autoIncrementPrimaryKeys()) {
            rs = stmt.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Unable to determine auto-generated ID for database record");
            }
            userBlock.setBlockId(rs.getInt(1));
        }
    } finally {
        // close only the statement and result set - leave the connection open for further use
        DatabaseConnection.closeConnection(null, stmt, rs);
    }
}

From source file:uk.ac.ebi.sail.server.data.DataManager.java

public Integer addProjection(ProjectionShadow p) throws ProjectionManagementException {
    Connection conn = null;/*  w w  w. j  a  va2s  .  c  o m*/
    ResultSet rst = null;
    try {

        Projection pj = p.createProjection();
        for (int clid : p.getClassifiers()) {
            Classifier cl = classifiers.get(clid);

            if (cl == null)
                throw new ProjectionManagementException("Invalid classifer ID=" + clid,
                        ProjectionManagementException.INV_CLASSIFIER_ID);

            pj.addClassifier(cl);
        }

        conn = dSrc.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(insertProjectionSQL, Statement.RETURN_GENERATED_KEYS);

        pstmt.setString(1, p.getName());
        pstmt.setString(2, p.getDescription());

        pstmt.executeUpdate();

        rst = pstmt.getGeneratedKeys();

        int id = -1;
        if (rst.next())
            id = rst.getInt(1);

        pstmt.close();

        pstmt = conn.prepareStatement(insertProjectionContentSQL);

        int n = 1;
        for (int clid : p.getClassifiers()) {
            pstmt.setInt(1, id);
            pstmt.setInt(2, clid);
            pstmt.setInt(3, n++);

            pstmt.executeUpdate();
        }

        pstmt.close();

        p.setId(id);

        projectionList.add(p);

        return id;

    } catch (SQLException e) {
        Log.error("SQL error", e);
        throw new ProjectionManagementException("SQL error", e, ProjectionManagementException.SQL_ERROR);
    } finally {
        if (rst != null)
            try {
                rst.close();
            } catch (SQLException e) {
            }

        if (conn != null)
            try {
                conn.close();
            } catch (SQLException e) {
                Log.error("Connection closing error", e);
            }

    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *//*w  ww  .ja  v a2s  .co m*/
public void insertVirtualWiki(VirtualWiki virtualWiki, Connection conn) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        int index = 1;
        if (!this.autoIncrementPrimaryKeys()) {
            stmt = conn.prepareStatement(STATEMENT_INSERT_VIRTUAL_WIKI);
            int virtualWikiId = this.nextVirtualWikiId(conn);
            virtualWiki.setVirtualWikiId(virtualWikiId);
            stmt.setInt(index++, virtualWiki.getVirtualWikiId());
        } else {
            stmt = conn.prepareStatement(STATEMENT_INSERT_VIRTUAL_WIKI_AUTO_INCREMENT,
                    Statement.RETURN_GENERATED_KEYS);
        }
        stmt.setString(index++, virtualWiki.getName());
        stmt.setString(index++, (virtualWiki.isDefaultRootTopicName() ? null : virtualWiki.getRootTopicName()));
        stmt.setString(index++, (virtualWiki.isDefaultLogoImageUrl() ? null : virtualWiki.getLogoImageUrl()));
        stmt.setString(index++,
                (virtualWiki.isDefaultMetaDescription() ? null : virtualWiki.getMetaDescription()));
        stmt.setString(index++, (virtualWiki.isDefaultSiteName() ? null : virtualWiki.getSiteName()));
        stmt.executeUpdate();
        if (this.autoIncrementPrimaryKeys()) {
            rs = stmt.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Unable to determine auto-generated ID for database record");
            }
            virtualWiki.setVirtualWikiId(rs.getInt(1));
        }
    } finally {
        // close only the statement and result set - leave the connection open for further use
        DatabaseConnection.closeConnection(null, stmt, rs);
    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *///from   w  w w.j  ava 2s.  c  o m
public void insertWikiFile(WikiFile wikiFile, int virtualWikiId, Connection conn) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        int index = 1;
        if (!this.autoIncrementPrimaryKeys()) {
            stmt = conn.prepareStatement(STATEMENT_INSERT_WIKI_FILE);
            int fileId = this.nextWikiFileId(conn);
            wikiFile.setFileId(fileId);
            stmt.setInt(index++, wikiFile.getFileId());
        } else {
            stmt = conn.prepareStatement(STATEMENT_INSERT_WIKI_FILE_AUTO_INCREMENT,
                    Statement.RETURN_GENERATED_KEYS);
        }
        stmt.setInt(index++, virtualWikiId);
        stmt.setString(index++, wikiFile.getFileName());
        stmt.setString(index++, wikiFile.getUrl());
        stmt.setString(index++, wikiFile.getMimeType());
        stmt.setInt(index++, wikiFile.getTopicId());
        stmt.setTimestamp(index++, wikiFile.getDeleteDate());
        stmt.setInt(index++, (wikiFile.getReadOnly() ? 1 : 0));
        stmt.setInt(index++, (wikiFile.getAdminOnly() ? 1 : 0));
        stmt.setLong(index++, wikiFile.getFileSize());
        stmt.executeUpdate();
        if (this.autoIncrementPrimaryKeys()) {
            rs = stmt.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Unable to determine auto-generated ID for database record");
            }
            wikiFile.setFileId(rs.getInt(1));
        }
    } finally {
        // close only the statement and result set - leave the connection open for further use
        DatabaseConnection.closeConnection(null, stmt, rs);
    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *///w ww . ja  v a2s.c o  m
public void insertWikiFileVersion(WikiFileVersion wikiFileVersion, Connection conn) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        int index = 1;
        if (!this.autoIncrementPrimaryKeys()) {
            stmt = conn.prepareStatement(STATEMENT_INSERT_WIKI_FILE_VERSION);
            int fileVersionId = this.nextWikiFileVersionId(conn);
            wikiFileVersion.setFileVersionId(fileVersionId);
            stmt.setInt(index++, wikiFileVersion.getFileVersionId());
        } else {
            stmt = conn.prepareStatement(STATEMENT_INSERT_WIKI_FILE_VERSION_AUTO_INCREMENT,
                    Statement.RETURN_GENERATED_KEYS);
        }
        if (wikiFileVersion.getUploadDate() == null) {
            Timestamp uploadDate = new Timestamp(System.currentTimeMillis());
            wikiFileVersion.setUploadDate(uploadDate);
        }
        stmt.setInt(index++, wikiFileVersion.getFileId());
        stmt.setString(index++, wikiFileVersion.getUploadComment());
        stmt.setString(index++, wikiFileVersion.getUrl());
        if (wikiFileVersion.getAuthorId() == null) {
            stmt.setNull(index++, Types.INTEGER);
        } else {
            stmt.setInt(index++, wikiFileVersion.getAuthorId());
        }
        stmt.setString(index++, wikiFileVersion.getAuthorDisplay());
        stmt.setTimestamp(index++, wikiFileVersion.getUploadDate());
        stmt.setString(index++, wikiFileVersion.getMimeType());
        stmt.setLong(index++, wikiFileVersion.getFileSize());
        stmt.executeUpdate();
        if (this.autoIncrementPrimaryKeys()) {
            rs = stmt.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Unable to determine auto-generated ID for database record");
            }
            wikiFileVersion.setFileVersionId(rs.getInt(1));
        }
    } finally {
        // close only the statement and result set - leave the connection open for further use
        DatabaseConnection.closeConnection(null, stmt, rs);
    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *//*w w  w  .  java2  s  .c o m*/
public void insertWikiGroup(WikiGroup group, Connection conn) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        int index = 1;
        if (!this.autoIncrementPrimaryKeys()) { // && group.getGroupId()>0) {
            stmt = conn.prepareStatement(STATEMENT_INSERT_GROUP);
            int groupId = this.nextWikiGroupId(conn);
            group.setGroupId(groupId);
            stmt.setInt(index++, group.getGroupId());
        } else {
            stmt = conn.prepareStatement(STATEMENT_INSERT_GROUP_AUTO_INCREMENT,
                    Statement.RETURN_GENERATED_KEYS);
        }
        stmt.setString(index++, group.getName());
        stmt.setString(index++, group.getDescription());
        stmt.executeUpdate();
        if (this.autoIncrementPrimaryKeys()) {
            rs = stmt.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Unable to determine auto-generated ID for database record");
            }
            group.setGroupId(rs.getInt(1));
        }
    } finally {
        // close only the statement and result set - leave the connection open for further use
        DatabaseConnection.closeConnection(null, stmt, rs);
    }
}