View Javadoc

1   /*
2    * org.riverock.dbrevision - Database revision engine
3    * For more information about DbRevision, please visit project site
4    * http://www.riverock.org
5    *
6    * Copyright (C) 2006-2006, Riverock Software, All Rights Reserved.
7    *
8    * Riverock - The Open-source Java Development Community
9    * http://www.riverock.org
10   *
11   *
12   * This library is free software; you can redistribute it and/or
13   * modify it under the terms of the GNU Lesser General Public
14   * License as published by the Free Software Foundation; either
15   * version 2.1 of the License, or (at your option) any later version.
16   *
17   * This library is distributed in the hope that it will be useful,
18   * but WITHOUT ANY WARRANTY; without even the implied warranty of
19   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20   * Lesser General Public License for more details.
21   *
22   * You should have received a copy of the GNU Lesser General Public
23   * License along with this library; if not, write to the Free Software
24   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25   */
26  package org.riverock.dbrevision.utils;
27  
28  import java.sql.PreparedStatement;
29  import java.sql.ResultSet;
30  import java.sql.SQLException;
31  import java.sql.Statement;
32  import java.sql.Types;
33  import java.sql.Connection;
34  
35  import org.apache.log4j.Logger;
36  
37  /**
38   * @author Sergei Maslyukov
39   *         Date: 14.12.2006
40   *         Time: 17:10:38
41   *         <p/>
42   *         $Id$
43   */
44  public class DbUtils {
45      private final static Logger log = Logger.getLogger(DbUtils.class);
46  
47      /**
48       * Get result of query as Long
49       *
50       * @param conn   db connection
51       * @param sql    query string
52       * @param params query parameters
53       * @param types  parameters types
54       * @return Long result
55       * @throws SQLException on error
56       */
57      @SuppressWarnings({"UnusedAssignment"})
58      public static Long getLongValue(final Connection conn, final String sql, final Object[] params, final int[] types)
59          throws SQLException {
60          Statement stmt = null;
61          PreparedStatement pstm;
62          ResultSet rs = null;
63  
64          try {
65              if (params == null) {
66                  stmt = conn.createStatement();
67                  rs = stmt.executeQuery(sql);
68              }
69              else {
70                  pstm = conn.prepareStatement(sql);
71                  for (int i = 0; i < params.length; i++) {
72                      if (types == null) {
73                          pstm.setObject(i + 1, params[i]);
74                      }
75                      else {
76                          pstm.setObject(i + 1, params[i], types[i]);
77                      }
78                  }
79  
80                  rs = pstm.executeQuery();
81                  stmt = pstm;
82              }
83  
84              if (rs.next()) {
85                  long tempLong = rs.getLong(1);
86                  if (rs.wasNull()) {
87                      return null;
88                  }
89  
90                  return tempLong;
91              }
92              return null;
93          }
94          catch (SQLException e) {
95              log.error("error getting long value from sql:\n" + sql, e);
96              throw e;
97          }
98          finally {
99              close(rs, stmt);
100             rs = null;
101             stmt = null;
102             pstm = null;
103         }
104     }
105 
106     /**
107      * выполнить sql
108      * @param conn connection
109      * @param query sql
110      * @param params parameters
111      * @param types types of parameters
112      * @return int count of updated records
113      * @throws SQLException on error
114      */
115     public static int runSQL(final Connection conn, final String query, final Object[] params, final int[] types)
116         throws SQLException {
117         int n = 0;
118         Statement stmt = null;
119         PreparedStatement pstm = null;
120 
121         try {
122             if (params == null) {
123                 stmt = conn.createStatement();
124                 n = stmt.executeUpdate(query);
125             } else {
126                 pstm = conn.prepareStatement(query);
127                 for (int i = 0; i < params.length; i++) {
128                     if (params[i] != null)
129                         pstm.setObject(i + 1, params[i], types[i]);
130                     else
131                         pstm.setNull(i + 1, types[i]);
132                 }
133 
134                 n = pstm.executeUpdate();
135                 stmt = pstm;
136             }
137         }
138         catch (SQLException e) {
139             log.error("SQL query:\n" + query);
140             try {
141                 if (params != null) {
142                     for (int ii = 0; ii < params.length; ii++)
143                         log.error("parameter #" + (ii + 1) + ": " + (params[ii] != null ? params[ii].toString() : null));
144                 }
145             }
146             catch (Throwable e1) {
147                 log.error("Error while output parameters: " + e1.toString());
148             }
149             log.error("SQLException", e);
150             throw e;
151         }
152         finally {
153             close(stmt);
154             stmt = null;
155             pstm = null;
156         }
157         return n;
158     }
159 
160     public static void setLong(final PreparedStatement ps, final int index, final Long data)
161         throws SQLException {
162         if (data != null) {
163             ps.setLong(index, data);
164         }
165         else {
166             ps.setNull(index, Types.NUMERIC);
167         }
168     }
169 
170     /**
171      * String f - name of field
172      * 
173      * @param rs ResultSet
174      * @param f name of field
175      * @return value as Long
176      * @throws java.sql.SQLException on error
177      */
178     public static Boolean getBoolean(final ResultSet rs, final String f) throws SQLException {
179         return getBoolean(rs, f, null);
180     }
181 
182     /**
183      * @param rs - ResultSet
184      * @param f - name of field
185      * @param def - default value
186      * @return value of column as Long
187      * @throws java.sql.SQLException on error
188      */
189     public static Boolean getBoolean(final ResultSet rs, final String f, final Boolean def) throws SQLException {
190 
191         if (rs == null || f == null) {
192             return def;
193         }
194 
195         try {
196             boolean temp = rs.getBoolean(f);
197             if (rs.wasNull()) {
198                 return def;
199             }
200 
201             return temp;
202         }
203         catch (SQLException exc) {
204             log.error("Error get Boolean field '" + f + "'", exc);
205             throw exc;
206         }
207     }
208 
209     /**
210      * String f - name of field
211      *
212      * @param rs ResultSet
213      * @param f name of field
214      * @return value as Long
215      * @throws java.sql.SQLException on error
216      */
217     public static Long getLong(final ResultSet rs, final String f)
218         throws SQLException {
219         return getLong(rs, f, null);
220     }
221 
222     /**
223      * @param rs - ResultSet
224      * @param f - name of field
225      * @param def - default value
226      * @return value of column as Long
227      * @throws java.sql.SQLException on error
228      */
229     public static Long getLong(final ResultSet rs, final String f, final Long def)
230         throws SQLException {
231 
232         if (rs == null || f == null) {
233             return def;
234         }
235 
236         try {
237             long temp = rs.getLong(f);
238             if (rs.wasNull()) {
239                 return def;
240             }
241 
242             return temp;
243         }
244         catch (SQLException exc) {
245             log.error("Error get Long field '" + f + "'", exc);
246             throw exc;
247         }
248     }
249 
250     /**
251      * ResultSet rs - ResultSet
252      * String f - name of field
253      */
254     public static Integer getInteger(final ResultSet rs, final String f)
255         throws SQLException {
256         return getInteger(rs, f, null);
257     }
258 
259     /**
260      * ResultSet rs - ResultSet
261      * String f - name of field
262      * int def - default value
263      */
264     public static Integer getInteger(final ResultSet rs, final String f, final Integer def)
265         throws SQLException {
266         if (rs == null || f == null) {
267             return def;
268         }
269 
270         try {
271             int temp = rs.getInt(f);
272             if (rs.wasNull()) {
273                 return def;
274             }
275 
276             return temp;
277         }
278         catch (SQLException exc) {
279             log.error("Error get Integer field '" + f + "' from ResultSet", exc);
280             throw exc;
281         }
282     }
283 
284     /**
285      * ResultSet rs - ResultSet
286      * String f - name of field
287      */
288     public static String getString(final ResultSet rs, final String f)
289         throws SQLException {
290         return getString(rs, f, null);
291     }
292 
293     /**
294      * ResultSet rs - ResultSet
295      * String f - name of field
296      * String def - default value
297      */
298     public static String getString(final ResultSet rs, final String f, final String def)
299         throws SQLException {
300         if (rs == null || f == null) {
301             return def;
302         }
303 
304         try {
305             Object obj = rs.getObject(f);
306             if (rs.wasNull()) {
307                 return def;
308             }
309 
310             return obj.toString();
311         }
312         catch (SQLException exc) {
313             log.error("Error get String field '" + f + "' from ResultSet, sql error code ", exc);
314             throw exc;
315         }
316     }
317 
318     public static void close(final ResultSet rs, final Statement st) {
319         if (rs != null) {
320             try {
321                 rs.close();
322             }
323             catch (Exception e01) {
324                 // catch SQLException
325             }
326         }
327         if (st != null) {
328             try {
329                 st.close();
330             }
331             catch (Exception e02) {
332                 // catch SQLException
333             }
334         }
335     }
336 
337     public static void close(final Statement st) {
338         if (st != null) {
339             try {
340                 st.close();
341             }
342             catch (SQLException e201) {
343                 // catch SQLException
344             }
345         }
346     }
347 
348     public static void close(final Connection conn) {
349         if (conn != null) {
350             try {
351                 conn.rollback();
352             }
353             catch (SQLException e201) {
354                 // catch SQLException
355             }
356             try {
357                 conn.close();
358             }
359             catch (SQLException e201) {
360                 // catch SQLException
361             }
362         }
363     }
364 }