1 /*
2 * This file is part of dependency-check-core.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * Copyright (c) 2013 Jeremy Long. All Rights Reserved.
17 */
18 package org.owasp.dependencycheck.utils;
19
20 import java.sql.PreparedStatement;
21 import java.sql.ResultSet;
22 import java.sql.SQLException;
23 import java.sql.Statement;
24 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29 *
30 * @author Jeremy Long
31 */
32 public final class DBUtils {
33
34 /**
35 * The logger.
36 */
37 private static final Logger LOGGER = LoggerFactory.getLogger(DBUtils.class);
38
39 /**
40 * Private constructor for a utility class.
41 */
42 private DBUtils() {
43 }
44
45 /**
46 * Returns the generated integer primary key for a newly inserted row.
47 *
48 * @param statement a prepared statement that just executed an insert
49 * @return a primary key
50 * @throws DatabaseException thrown if there is an exception obtaining the key
51 */
52 public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException {
53 ResultSet rs = null;
54 int id = 0;
55 try {
56 rs = statement.getGeneratedKeys();
57 if (!rs.next()) {
58 throw new DatabaseException("Unable to get primary key for inserted row");
59 }
60 id = rs.getInt(1);
61 } catch (SQLException ex) {
62 throw new DatabaseException("Unable to get primary key for inserted row");
63 } finally {
64 closeResultSet(rs);
65 }
66 return id;
67 }
68
69 /**
70 * Closes the given statement object ignoring any exceptions that occur.
71 *
72 * @param statement a Statement object
73 */
74 public static void closeStatement(Statement statement) {
75 if (statement != null) {
76 try {
77 statement.close();
78 } catch (SQLException ex) {
79 LOGGER.trace(statement.toString(), ex);
80 }
81 }
82 }
83
84 /**
85 * Closes the result set capturing and ignoring any SQLExceptions that occur.
86 *
87 * @param rs a ResultSet to close
88 */
89 public static void closeResultSet(ResultSet rs) {
90 if (rs != null) {
91 try {
92 rs.close();
93 } catch (SQLException ex) {
94 LOGGER.trace(rs.toString(), ex);
95 }
96 }
97 }
98 }