Source Code Cross Referenced for JdbcUtilities.java in  » Database-Client » iSQL-Viewer » org » isqlviewer » sql » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database Client » iSQL Viewer » org.isqlviewer.sql 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * The contents of this file are subject to the Mozilla Public License
003:         * Version 1.1 (the "License"); you may not use this file except in
004:         * compliance with the License. You may obtain a copy of the License at
005:         * http://www.mozilla.org/MPL/
006:         *
007:         * Software distributed under the License is distributed on an "AS IS"
008:         * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
009:         * License for the specific language governing rights and limitations
010:         * under the License.
011:         * 
012:         * The Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
013:         *
014:         * The Initial Developer of the Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
015:         * Portions created by Mark A. Kobold are Copyright (C) 2000-2007. All Rights Reserved.
016:         *
017:         * Contributor(s): 
018:         *  Mark A. Kobold [mkobold <at> isqlviewer <dot> com].
019:         *  
020:         * If you didn't download this code from the following link, you should check
021:         * if you aren't using an obsolete version: http://www.isqlviewer.com
022:         */
023:        package org.isqlviewer.sql;
024:
025:        import java.io.IOException;
026:        import java.lang.reflect.Field;
027:        import java.lang.reflect.InvocationTargetException;
028:        import java.lang.reflect.Method;
029:        import java.math.BigDecimal;
030:        import java.sql.Blob;
031:        import java.sql.Clob;
032:        import java.sql.DatabaseMetaData;
033:        import java.sql.PreparedStatement;
034:        import java.sql.ResultSet;
035:        import java.sql.SQLException;
036:        import java.sql.Time;
037:        import java.sql.Timestamp;
038:        import java.sql.Types;
039:        import java.text.Format;
040:        import java.text.ParseException;
041:        import java.util.Arrays;
042:        import java.util.Date;
043:        import java.util.HashMap;
044:        import java.util.Hashtable;
045:        import java.util.Map;
046:        import java.util.Vector;
047:
048:        /**
049:         * Utility class for dealing with JDBC oriented tasks.
050:         * <p>
051:         * None of the methods that deal with ResultSets will actually close the ResultSet when completed, a call to the method
052:         * first is called before and after each method is finished executing the defined function.
053:         * <p>
054:         * A small note about methods that use a the ResultSetViewer object as a parameter to the method is that if the
055:         * ResultSetViewer is null and an SQLException occurs an attempt will be made to add the respecting exception as a
056:         * warning to the given ResultSet object. So it recommended that if you want to know if an SQLException occured without
057:         * using the ResultSetViewer check for warnings on the ResultSet after method invocation.
058:         * 
059:         * @author Markus A. Kobold &lt;mkobold at sprintpcs dot com&gt;
060:         */
061:        public final class JdbcUtilities {
062:
063:            // private final static String RESULT_RESERVED_CHARS = "srctfzwCST";
064:
065:            private JdbcUtilities() {
066:
067:                // nothing to do or see here.
068:            }
069:
070:            /**
071:             * @return
072:             */
073:            public synchronized static Map<String, Object> extractMetadata(
074:                    DatabaseMetaData dmd) {
075:
076:                Class<? extends DatabaseMetaData> c = dmd.getClass();
077:                Method[] methods = c.getMethods();
078:                Hashtable<String, Object> properties = new Hashtable<String, Object>(
079:                        methods.length);
080:                Object[] p = new Object[0];
081:
082:                for (int i = 0; i < methods.length; i++) {
083:                    String methodName = methods[i].getName();
084:                    try {
085:                        if (methodName.startsWith("get")) {
086:                            Class returnType = methods[i].getReturnType();
087:                            methodName = methodName.substring(3);
088:                            if (returnType.isPrimitive()
089:                                    || returnType == String.class) {
090:                                Object methodResult = methods[i].invoke(dmd, p);
091:                                properties.put(methodName, methodResult);
092:                            }
093:                        }
094:                    } catch (AbstractMethodError ame) {
095:                        properties.put(methodName, "");
096:                    } catch (IllegalArgumentException e) {
097:                        e.printStackTrace();
098:                    } catch (IllegalAccessException e) {
099:                        e.printStackTrace();
100:                    } catch (InvocationTargetException e) {
101:                        e.printStackTrace();
102:                    }
103:                }
104:                return properties;
105:            }
106:
107:            /**
108:             * Checks if the ResultSet is deemed updatable.
109:             * <p>
110:             * Basically if the ResultSet has the UPDATABLE concurrency and is not of the FORWARD_ONLY type this method will
111:             * return true, IF the driver decides to throw exception when attempting to query this information this method will
112:             * always return false.
113:             * 
114:             * @see ResultSet#getConcurrency()
115:             * @see ResultSet#getType()
116:             * @param rs to check for updatability.
117:             * @return true if the ResultSet should support updates.
118:             */
119:            public static boolean isUpdatable(ResultSet rs) {
120:
121:                try {
122:                    int concur = rs.getConcurrency();
123:                    int type = rs.getType();
124:                    boolean updatable = (concur == ResultSet.CONCUR_UPDATABLE);
125:                    boolean scrollable = (type == ResultSet.TYPE_SCROLL_INSENSITIVE || type == ResultSet.TYPE_SCROLL_SENSITIVE);
126:                    return updatable && scrollable;
127:                } catch (Throwable t) {
128:                    return false;
129:                }
130:            }
131:
132:            /**
133:             * Helper method for determining if a given type is one of the date SQL types.
134:             * <p>
135:             * If the type equals DATE,TIME,TIMESTAMP then this will return true otherwise false.
136:             * 
137:             * @see Types
138:             * @param type SQL-Type to check
139:             * @return true if the given type represents Date objects
140:             */
141:            public static boolean isDateType(int type) {
142:
143:                switch (type) {
144:                case Types.DATE:
145:                case Types.TIME:
146:                case Types.TIMESTAMP:
147:                    return true;
148:                default:
149:                    return false;
150:                }
151:            }
152:
153:            /**
154:             * Helper method for determining if a given type is one of the String SQL types.
155:             * <p>
156:             * If the type equals CHAR,VARCHAR,LONGVARCHAR then this will return true otherwise false.
157:             * 
158:             * @see Types
159:             * @param type SQL-Type to check
160:             * @return true if the given type represents String objects
161:             */
162:            public static boolean isStringType(int type) {
163:
164:                switch (type) {
165:                case Types.CHAR:
166:                case Types.LONGVARCHAR:
167:                case Types.VARCHAR:
168:                    return true;
169:                default:
170:                    return false;
171:                }
172:            }
173:
174:            /**
175:             * Helper method for determining if a given type is one of the Boolean SQL types.
176:             * <p>
177:             * If the type equals BIT, BOOLEAN then this will return true otherwise false.
178:             * 
179:             * @see Types
180:             * @param type SQL-Type to check
181:             * @return true if the given type represents boolean objects
182:             */
183:            public static boolean isBooleanType(int type) {
184:
185:                switch (type) {
186:                case Types.BIT:
187:                case Types.BOOLEAN:
188:                    return true;
189:                default:
190:                    return false;
191:                }
192:            }
193:
194:            /**
195:             * Helper method for determining if a given type is one of the numerical SQL types.
196:             * <p>
197:             * If the type equals BIGINT,DECIMAL,DOUBLE,FLOAT,INTEGER,NUMERIC,REAL,SMALLINT, and TINYINT then this will return
198:             * true otherwise false.
199:             * 
200:             * @see Types
201:             * @param type SQL-Type to check
202:             * @return true if the given type represents numerical objects
203:             */
204:            public static boolean isNumberType(int type) {
205:
206:                switch (type) {
207:                case Types.BIGINT:
208:                case Types.DECIMAL:
209:                case Types.DOUBLE:
210:                case Types.FLOAT:
211:                case Types.INTEGER:
212:                case Types.NUMERIC:
213:                case Types.REAL:
214:                case Types.SMALLINT:
215:                case Types.TINYINT:
216:                    return true;
217:                default:
218:                    return false;
219:                }
220:            }
221:
222:            /**
223:             * Attempts to convert Object to it's standard type.
224:             * <p>
225:             * This method does make a fair attempt at conversion however it obviously can't convert everything. This method is
226:             * mainly to address working with the configurePreparedStatements as those method make the assumptions that the
227:             * objects are of type and simply casts them when appropriate.
228:             * <p>
229:             * Here is a rundown of what SQL Types goto what types. If the type is not listed here then object passed in will be
230:             * passed back.
231:             * <p>
232:             * Types :
233:             * <ul>
234:             * <li>CHAR, VARCHAR -&gt; {@link String}.
235:             * <li>TINYINT -&gt; {@link Byte}.
236:             * <li>SMALLINT -&gt; {@link Short}.
237:             * <li>INTEGER -&gt; {@link Integer}.
238:             * <li>BIGINT -&gt; {@link Long}.
239:             * <li>DOUBLE,FLOAT -&gt; {@link Double}.
240:             * <li>NUMERIC, DECIMAL -&gt; {@link BigDecimal}
241:             * <li>BOOLEAN, BIT -&gt; {@link Boolean}
242:             * <li>LONGVARBINARY, VARBINARY, BLOB -&gt; {@link ByteArrayBlob}
243:             * <li>CLOB, LONGVARCHAR -&gt; {@link ByteArrayClob}.
244:             * <li>DATE -&gt; {@link java.sql.Date}
245:             * <li>TIME -&gt; {@link Time}
246:             * <li>TIMESTAMP -&gt; {@link Timestamp}
247:             * </ul>
248:             * Anything not on the above list will not be converted to anything.
249:             * 
250:             * @see Types
251:             * @see #configurePreparedStatement(PreparedStatement, int, Object, int, boolean)
252:             * @param data to convert
253:             * @param type SQL type to convert to.
254:             * @param fmt object to use if parsing the data is required.
255:             * @return converted object.
256:             * @throws ParseException if using the format object parsing exception occurs.
257:             */
258:            public static Object convertValue(Object data, int type, Format fmt)
259:                    throws ParseException, IOException {
260:
261:                if (data == null && type != Types.NULL) {
262:                    throw new IllegalArgumentException("null ("
263:                            + getTypeforValue(type) + ")");
264:                } else if (data == null) {
265:                    return null;
266:                }
267:
268:                switch (type) {
269:                case Types.NULL:
270:                    return null;
271:
272:                case Types.CHAR:
273:                case Types.VARCHAR:
274:                    return data.toString();
275:
276:                case Types.TINYINT:
277:                    if (data instanceof  Number) {
278:                        if (data instanceof  Byte) {
279:                            return data;
280:                        }
281:                        Number numb = (Number) data;
282:                        return new Byte(numb.byteValue());
283:                    }
284:                    String txt = data.toString().trim();
285:                    if (txt.length() == 0) {
286:                        txt = "0";
287:                    }
288:
289:                    try {
290:                        byte bite = Byte.parseByte(txt);
291:                        return new Byte(bite);
292:                    } catch (Throwable t) {
293:                        if (fmt == null) {
294:                            throw new IllegalArgumentException(data.toString());
295:                        }
296:
297:                        Number numb = (Number) fmt.parseObject(data.toString());
298:                        return new Byte(numb.byteValue());
299:                    }
300:
301:                case Types.SMALLINT:
302:                    if (data instanceof  Number) {
303:                        if (data instanceof  Short) {
304:                            return data;
305:                        }
306:                        Number numb = (Number) data;
307:                        return new Short(numb.shortValue());
308:                    }
309:
310:                    txt = data.toString().trim();
311:                    if (txt.length() == 0) {
312:                        txt = "0";
313:                    }
314:
315:                    try {
316:                        short shrt = Short.parseShort(txt);
317:                        return new Short(shrt);
318:                    } catch (Throwable t) {
319:                        if (fmt == null) {
320:                            throw new IllegalArgumentException(data.toString());
321:                        }
322:
323:                        Number numb = (Number) fmt.parseObject(data.toString());
324:                        return new Short(numb.shortValue());
325:                    }
326:
327:                case Types.INTEGER:
328:                    if (data instanceof  Number) {
329:                        if (data instanceof  Integer) {
330:                            return data;
331:                        }
332:                        Number numb = (Number) data;
333:                        return new Integer(numb.intValue());
334:                    }
335:
336:                    txt = data.toString().trim();
337:                    if (txt.length() == 0) {
338:                        txt = "0";
339:                    }
340:
341:                    try {
342:                        int val = Integer.parseInt(txt);
343:                        return new Integer(val);
344:                    } catch (Throwable t) {
345:                        if (fmt == null) {
346:                            throw new IllegalArgumentException(data.toString()
347:                                    .trim());
348:                        }
349:
350:                        Number numb = (Number) fmt.parseObject(data.toString());
351:                        return new Integer(numb.intValue());
352:                    }
353:
354:                case Types.BIGINT:
355:                    if (data instanceof  Number) {
356:                        if (data instanceof  Long) {
357:                            return data;
358:                        }
359:                        Number numb = (Number) data;
360:                        return new Long(numb.longValue());
361:                    }
362:                    txt = data.toString().trim();
363:                    if (txt.length() == 0) {
364:                        txt = "0";
365:                    }
366:
367:                    try {
368:                        long val = Long.parseLong(txt);
369:                        return new Long(val);
370:                    } catch (Throwable t) {
371:                        if (fmt == null) {
372:                            throw new IllegalArgumentException(data.toString());
373:                        }
374:
375:                        Number numb = (Number) fmt.parseObject(data.toString());
376:                        return new Long(numb.longValue());
377:                    }
378:
379:                case Types.DOUBLE:
380:                case Types.FLOAT:
381:                    if (data instanceof  Number) {
382:                        if (data instanceof  Double) {
383:                            return data;
384:                        }
385:                        Number numb = (Number) data;
386:                        return new Double(numb.doubleValue());
387:                    }
388:                    txt = data.toString().trim();
389:                    if (txt.length() == 0) {
390:                        txt = "0";
391:                    }
392:
393:                    try {
394:                        double val = Double.parseDouble(txt);
395:                        return new Double(val);
396:                    } catch (Throwable t) {
397:                        if (fmt == null) {
398:                            throw new IllegalArgumentException(data.toString());
399:                        }
400:
401:                        Number numb = (Number) fmt.parseObject(data.toString());
402:                        return new Double(numb.doubleValue());
403:                    }
404:
405:                case Types.NUMERIC:
406:                case Types.DECIMAL:
407:                    if (data instanceof  Number) {
408:                        if (data instanceof  BigDecimal) {
409:                            return data;
410:                        }
411:                        Number numb = (Number) data;
412:                        return new BigDecimal(numb.doubleValue());
413:                    }
414:
415:                    txt = data.toString().trim();
416:                    if (txt.length() == 0) {
417:                        txt = "0";
418:                    }
419:
420:                    try {
421:                        return new BigDecimal(txt);
422:                    } catch (Throwable t) {
423:                        if (fmt == null) {
424:                            throw new IllegalArgumentException(data.toString());
425:                        }
426:
427:                        Number numb = (Number) fmt.parseObject(data.toString());
428:                        return new BigDecimal(numb.doubleValue());
429:                    }
430:
431:                case Types.BOOLEAN:
432:                case Types.BIT:
433:                    if (data instanceof  Boolean) {
434:                        return data;
435:                    }
436:
437:                    try {
438:                        return Boolean.valueOf(data.toString());
439:                    } catch (Throwable t) {
440:                        if (fmt == null) {
441:                            throw new IllegalArgumentException(data.toString());
442:                        }
443:
444:                        return fmt.parseObject(data.toString());
445:                    }
446:
447:                case Types.LONGVARBINARY:
448:                case Types.VARBINARY:
449:                case Types.BLOB:
450:                    if (data instanceof  byte[]) {
451:                        return new ByteArrayBlob((byte[]) data);
452:                    } else if (data instanceof  Blob) {
453:                        byte[] blob = null;
454:                        try {
455:                            Blob b = (Blob) data;
456:                            blob = b.getBytes(0, (int) b.length());
457:                        } catch (SQLException sqle) {
458:                            blob = data.toString().getBytes();
459:                        }
460:                        return new ByteArrayBlob(blob);
461:                    } else if (data instanceof  Clob) {
462:                        byte[] blob = null;
463:                        try {
464:                            Clob c = (Clob) data;
465:                            blob = c.getSubString(0, (int) c.length())
466:                                    .getBytes();
467:                        } catch (SQLException sqle) {
468:                            blob = data.toString().getBytes();
469:                        }
470:                        return new ByteArrayBlob(blob);
471:                    } else {
472:                        if (fmt == null) {
473:                            return data.toString().getBytes();
474:                        }
475:
476:                        return fmt.parseObject(data.toString());
477:                    }
478:                case Types.CLOB:
479:                case Types.LONGVARCHAR:
480:                    try {
481:                        if (data instanceof  Clob) {
482:                            Clob clob = (Clob) data;
483:                            try {
484:                                return new ByteArrayClob(clob.getSubString(0,
485:                                        (int) clob.length()));
486:                            } catch (SQLException e) {
487:                                throw new ParseException(e.getMessage(), 0);
488:                            }
489:                        } else if (data instanceof  char[]) {
490:                            return new ByteArrayClob((char[]) data);
491:                        } else if (data instanceof  String) {
492:                            return new ByteArrayClob(data.toString());
493:                        } else if (data instanceof  Blob) {
494:                            String c = null;
495:                            try {
496:                                Blob b = (Blob) data;
497:                                c = new String(b.getBytes(0, (int) b.length()));
498:                            } catch (SQLException sqle) {
499:                                c = data.toString();
500:                            }
501:                            return new ByteArrayClob(c);
502:                        } else {
503:                            if (fmt == null) {
504:                                return new ByteArrayClob(data.toString());
505:                            }
506:
507:                            return fmt.parseObject(data.toString());
508:                        }
509:                    } catch (IOException ioe) {
510:                        return null;
511:                    }
512:                case Types.DATE:
513:                    if (data instanceof  Date) {
514:                        Date date = (Date) data;
515:                        return new java.sql.Date(date.getTime());
516:                    } else if (data instanceof  Number) {
517:                        Number numb = (Number) data;
518:                        return new java.sql.Date(numb.longValue());
519:                    } else {
520:                        if (fmt == null) {
521:                            throw new IllegalArgumentException(data.toString());
522:                        }
523:
524:                        Date date = (Date) fmt.parseObject(data.toString());
525:                        return new java.sql.Date(date.getTime());
526:                    }
527:
528:                case Types.TIME:
529:                    if (data instanceof  Time) {
530:                        return data;
531:                    } else if (data instanceof  Date) {
532:                        Date date = (Date) data;
533:                        return new Time(date.getTime());
534:                    } else if (data instanceof  Number) {
535:                        Number numb = (Number) data;
536:                        return new Time(numb.longValue());
537:                    } else {
538:                        if (fmt == null) {
539:                            throw new IllegalArgumentException(data.toString());
540:                        }
541:
542:                        Date date = (Date) fmt.parseObject(data.toString());
543:                        return new Time(date.getTime());
544:                    }
545:
546:                case Types.TIMESTAMP:
547:                    if (data instanceof  Time) {
548:                        return data;
549:                    } else if (data instanceof  Date) {
550:                        Date date = (Date) data;
551:                        return new Timestamp(date.getTime());
552:                    } else if (data instanceof  Number) {
553:                        Number numb = (Number) data;
554:                        return new Timestamp(numb.longValue());
555:                    } else {
556:                        if (fmt == null) {
557:                            throw new IllegalArgumentException(data.toString());
558:                        }
559:
560:                        Date date = (Date) fmt.parseObject(data.toString());
561:                        return new Timestamp(date.getTime());
562:                    }
563:
564:                default:
565:                    return data;
566:
567:                }
568:
569:            }
570:
571:            /**
572:             * Refelcts to get SQL Type constant by name.
573:             * <p>
574:             * Simple reflection utility to get the proper constant for the Type name.
575:             * 
576:             * @see Types
577:             * @see #getTypeforValue(int)
578:             * @param name valid field name in Types
579:             * @return int representing the proper constant.
580:             */
581:            public static int getTypeforName(String name) {
582:
583:                try {
584:                    Class c = Types.class;
585:                    return c.getField(name.toUpperCase()).getInt(null);
586:                } catch (Exception e) {
587:                    return Types.VARCHAR;
588:                }
589:            }
590:
591:            /**
592:             * Reverse lookup of a type name based on the constant.
593:             * <p>
594:             * This will iterate through the declared fields of the Types.class and once the correct field int value match the
595:             * given type it will return the name of the field.
596:             * 
597:             * @see #getTypeforName(String)
598:             * @see Types
599:             * @param type to get Field name for.
600:             * @return name of the field of Types.class based on the given constant.
601:             */
602:            public static String getTypeforValue(int type) {
603:
604:                try {
605:                    Class c = Types.class;
606:                    Field[] flds = c.getDeclaredFields();
607:                    for (int i = 0; i < flds.length; i++) {
608:                        Field f = flds[i];
609:                        if (f.getInt(null) == type) {
610:                            return f.getName();
611:                        }
612:                    }
613:                    return null;
614:                } catch (Exception e) {
615:                    return null;
616:                }
617:
618:            }
619:
620:            /**
621:             * Returns a list of Strings of valid Java SQL types.
622:             * <p>
623:             * This method reflects through {
624:             * 
625:             * @link java.sql.Types } object to get the names of all the fields in that object and returns them as an array.
626:             * @param sorted determines to sort the list or not.
627:             * @return String[] list of Types fields by name.
628:             */
629:            public static String[] getSQLTypes(boolean sorted) {
630:
631:                Vector<String> list = new Vector<String>();
632:                try {
633:                    Class c = Types.class;
634:                    Field[] types = c.getFields();
635:                    for (int i = 0; i < types.length; i++)
636:                        try {
637:                            list.add(types[i].getName());
638:                        } catch (Exception e) {
639:                            continue;
640:                        }
641:                } catch (Exception e) {
642:                }
643:                String[] data = list.toArray(new String[list.size()]);
644:                if (sorted) {
645:                    Arrays.sort(data);
646:                }
647:                return data;
648:            }
649:
650:            public static HashMap<String, Integer> getNativeTypeMap(
651:                    DatabaseMetaData metaData) {
652:
653:                HashMap<String, Integer> map = new HashMap<String, Integer>();
654:                ResultSet set = null;
655:                try {
656:                    set = metaData.getTypeInfo();
657:                    while (set.next()) {
658:                        String name = set.getString("TYPE_NAME");
659:                        Integer sqlType = new Integer(set.getInt("DATA_TYPE"));
660:                        map.put(name, sqlType);
661:                    }
662:                } catch (Throwable t) {
663:                    map.clear();
664:                } finally {
665:                    try {
666:                        if (set != null) {
667:                            set.close();
668:                        }
669:                    } catch (Throwable t) {
670:                    }
671:                }
672:                return map;
673:            }
674:
675:            /**
676:             * Helper method to assist with creating insert commands for prepared statements.
677:             * <p>
678:             * This will create an SQL statement in the following format. <br>
679:             * INSERT INTO {Table} ({Colums[0],},.., {Columns[n]}) VALUES(?,..,?) <br>
680:             * This method will return null if an exception occurs.
681:             * 
682:             * @param Table Name of table you wish to insert into.
683:             * @param Columns List of column names to declare values for.
684:             * @return Generated SQL statement for use with creating prepared statements.
685:             */
686:            public static String generatePreparedInsertRequest(String Table,
687:                    String[] Columns) {
688:
689:                if (Columns.length >= 1 && Table != null) {
690:                    StringBuffer sql = new StringBuffer("INSERT INTO ");
691:                    sql.append(Table);
692:                    sql.append(" (");
693:                    for (int i = 0; i < Columns.length - 1; i++) {
694:                        sql.append(Columns[i]);
695:                        sql.append(", ");
696:                    }
697:
698:                    sql.append(Columns[Columns.length - 1]);
699:                    sql.append(") VALUES (");
700:
701:                    for (int i = 0; i < Columns.length - 1; i++)
702:                        sql.append("?, ");
703:
704:                    sql.append("?)");
705:                    return sql.toString();
706:                }
707:
708:                return null;
709:            }
710:
711:            /**
712:             * Helper method to assist with creating update commands for prepared statements.
713:             * <p>
714:             * This will create an SQL statement in the following format. <br>
715:             * UPDATE {Table} SET {Colums[0]=?,},.., {Columns[n]=?} WHERE {whereClause} <br>
716:             * This method will return null if an exception occurs.
717:             * 
718:             * @param Table Name of table you wish to update.
719:             * @param Columns List of column names to update.
720:             * @param whereClause Standard SQL where clause for this update.
721:             * @return Generated SQL statement for use with creating prepared statements.
722:             */
723:            public static String generatePreparedUpdateRequest(String Table,
724:                    String[] Columns, String whereClause) {
725:
726:                try {
727:                    StringBuffer sql = new StringBuffer("UPDATE ");
728:                    sql.append(Table);
729:                    sql.append(" SET (");
730:                    for (int i = 0; i < Columns.length - 1; i++) {
731:                        sql.append(Columns[i]);
732:                        sql.append("=?, ");
733:                    }
734:
735:                    sql.append(Columns[Columns.length - 1]);
736:
737:                    sql.append("=?)");
738:                    if (whereClause != null && whereClause.trim().length() >= 1) {
739:                        sql.append(" WHERE ");
740:                        sql.append(whereClause);
741:                    }
742:                    return sql.toString();
743:
744:                } catch (Throwable t) {
745:                    return null;
746:                }
747:            }
748:
749:            /**
750:             * Helper method to the other configurePreparedStatement method.
751:             * <p>
752:             * This method consists of a simple for loop that calls the other configurePreparedStatement method.
753:             * 
754:             * @see #configurePreparedStatement(PreparedStatement, int, Object, int, boolean)
755:             * @param ps PreparedStatement to configure.
756:             * @param data objects to set in the statement
757:             * @param type SQL-Types for each of the object.
758:             * @throws SQLException if error occurs setting the objects in the prepared statement.
759:             * @throws NullPointerException if data or type is null
760:             * @throws IllegalArgumentException if the data.length != type.length
761:             */
762:            public static void configurePreparedStatement(PreparedStatement ps,
763:                    Object[] data, int[] type, boolean convert)
764:                    throws SQLException {
765:
766:                if (data == null || type == null) {
767:                    throw new NullPointerException();
768:                }
769:
770:                if (data.length != type.length) {
771:                    throw new IllegalArgumentException();
772:                }
773:
774:                for (int i = 0; i < data.length; i++) {
775:                    configurePreparedStatement(ps, i + 1, data[i], type[i],
776:                            convert);
777:                }
778:
779:            }
780:
781:            /**
782:             * Helper method set data parameters of a PreparedStatement.
783:             * <p>
784:             * This method does make the assumption that the given object is of the correct type as this method will simply cast
785:             * the object to the appropriate class based on the given SQL-Type. The logic as to what type should be what object
786:             * is detailed in the convert method, as it is recommend to call convert before this method as the successful
787:             * execution of convert will most likely ensure success of this method.
788:             * <p>
789:             * If the given value is null setNull(int,int) will be called on the statement and return immediately.
790:             * 
791:             * @see #convertValue(Object, int, Format)
792:             * @param index of the given parameter in the statement (index >= 1)
793:             * @param ps PreparedStatement to configure.
794:             * @param type for the given data object.
795:             * @throws SQLException if error occurs setting data.
796:             */
797:            public static void configurePreparedStatement(PreparedStatement ps,
798:                    int index, Object value, int type, boolean convert)
799:                    throws SQLException {
800:
801:                if (value == null) {
802:                    ps.setNull(index, type);
803:                    return;
804:                }
805:
806:                if (convert) {
807:                    try {
808:                        convertValue(value, type, null);
809:                    } catch (ParseException pe) {
810:                        throw new SQLException(pe.getMessage());
811:                    } catch (IOException e) {
812:                        throw new SQLException(e.getMessage());
813:                    }
814:                }
815:
816:                switch (type) {
817:                case Types.CHAR:
818:                case Types.VARCHAR:
819:                    ps.setString(index, (String) value);
820:                    break;
821:
822:                case Types.TINYINT:
823:                    ps.setByte(index, ((Number) value).byteValue());
824:                    break;
825:
826:                case Types.SMALLINT:
827:                    ps.setShort(index, ((Number) value).shortValue());
828:                    break;
829:
830:                case Types.INTEGER:
831:                    ps.setInt(index, ((Number) value).intValue());
832:                    break;
833:
834:                case Types.REAL:
835:                    ps.setFloat(index, ((Number) value).floatValue());
836:                    break;
837:
838:                case Types.BIGINT:
839:                    ps.setLong(index, ((Number) value).longValue());
840:                    break;
841:
842:                case Types.DOUBLE:
843:                case Types.FLOAT:
844:                    ps.setDouble(index, ((Number) value).doubleValue());
845:                    break;
846:
847:                case Types.NUMERIC:
848:                case Types.DECIMAL:
849:                    ps.setBigDecimal(index, (BigDecimal) value);
850:                    break;
851:
852:                case Types.BOOLEAN:
853:                case Types.BIT:
854:                    ps.setBoolean(index, ((Boolean) value).booleanValue());
855:                    break;
856:
857:                case Types.BLOB:
858:                    ps.setBlob(index, (Blob) value);
859:                    break;
860:
861:                case Types.CLOB:
862:                    ps.setClob(index, (Clob) value);
863:                    break;
864:
865:                case Types.DATE:
866:                    ps.setDate(index, (java.sql.Date) value);
867:                    break;
868:
869:                case Types.TIME:
870:                    ps.setTime(index, (Time) value);
871:                    break;
872:
873:                case Types.TIMESTAMP:
874:                    ps.setTimestamp(index, (Timestamp) value);
875:                    break;
876:
877:                case Types.LONGVARBINARY:
878:                case Types.VARBINARY:
879:                    ByteArrayBlob blob = (ByteArrayBlob) value;
880:                    ps.setBinaryStream(index, blob.getBinaryStream(),
881:                            (int) blob.length());
882:                    break;
883:
884:                case Types.LONGVARCHAR:
885:                    ByteArrayClob clob = (ByteArrayClob) value;
886:                    ps.setCharacterStream(index, clob.getCharacterStream(),
887:                            (int) clob.length());
888:                    break;
889:
890:                default:
891:                    ps.setObject(index, value);
892:                    break;
893:
894:                }
895:            }
896:
897:            public static Object getValueForType(ResultSet set, int type,
898:                    int idx) throws SQLException {
899:
900:                Object data = null;
901:                try {
902:                    switch (type) {
903:                    case Types.DATE:
904:                        data = set.getDate(idx);
905:                        break;
906:                    case Types.TINYINT:
907:                        data = new Byte(set.getByte(idx));
908:                        break;
909:                    case Types.SMALLINT:
910:                        data = new Short(set.getShort(idx));
911:                        break;
912:                    case Types.TIMESTAMP:
913:                        data = set.getTimestamp(idx);
914:                        break;
915:                    case Types.TIME:
916:                        data = set.getTime(idx);
917:                        break;
918:                    case Types.INTEGER:
919:                        data = new Integer(set.getInt(idx));
920:                        break;
921:                    case Types.DECIMAL:
922:                    case Types.NUMERIC:
923:                        data = set.getBigDecimal(idx);
924:                        break;
925:                    case Types.DOUBLE:
926:                    case Types.FLOAT:
927:                    case Types.REAL:
928:                        data = new Double(set.getDouble(idx));
929:                        break;
930:                    case Types.BIGINT:
931:                        data = new Long(set.getLong(idx));
932:                        break;
933:                    case Types.BIT:
934:                    case Types.BOOLEAN:
935:                        data = new Boolean(set.getBoolean(idx));
936:                        break;
937:                    case Types.LONGVARBINARY:
938:                    case Types.VARBINARY:
939:                    case Types.BINARY:
940:                        data = new ByteArrayBlob(set.getBytes(idx));
941:                        break;
942:                    case Types.LONGVARCHAR:
943:                    case Types.VARCHAR:
944:                    case Types.CHAR:
945:                        data = set.getString(idx);
946:                        break;
947:                    case Types.BLOB:
948:                        data = set.getBlob(idx);
949:                        break;
950:                    case Types.CLOB:
951:                        data = set.getClob(idx);
952:                        break;
953:                    case Types.REF:
954:                        data = set.getRef(idx);
955:                        break;
956:                    case Types.ARRAY:
957:                        data = set.getArray(idx);
958:                        break;
959:                    case Types.DISTINCT:
960:                        data = set.getObject(idx);
961:                        break;
962:                    default:
963:                        data = set.getObject(idx);
964:                        break;
965:
966:                    }
967:                } catch (SQLException sqle) {
968:                    // String[] p = new String[]{Integer.toString(idx), JdbcUtilities.getTypeforValue(type), sqle.getMessage()};
969:                    String msg = sqle.toString();// BasicUtilities.getString("Resultset_Pull_Error", p);
970:                    System.err.println(msg);
971:                    throw sqle;
972:                } catch (Throwable t) {
973:                    throw new RuntimeException(t);
974:                }
975:
976:                try {
977:                    if (set.wasNull()) {
978:                        data = null;
979:                    }
980:                } catch (Throwable t) {
981:                }
982:                return data;
983:            }
984:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.