KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > utils > SqlUtils


1 package com.tonbeller.wcf.utils;
2
3 import java.sql.Time JavaDoc;
4
5 import org.apache.log4j.Logger;
6
7 /**
8  * @author av
9  * @since 01.02.2005
10  */

11 public class SqlUtils {
12   
13   private static Logger logger = Logger.getLogger(SqlUtils.class);
14   
15   private SqlUtils() {}
16   
17
18   /**
19    * replaces '\n' with ' ' because DB2 does not like linefeeds in SQL Statements
20    */

21   public static final String JavaDoc convStatement(String JavaDoc genstmt) {
22     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
23     int n = genstmt.length();
24     for (int i = 0; i < n; i++) {
25       char c = genstmt.charAt(i);
26       if (Character.isWhitespace(c))
27         sb.append(' ');
28       else
29         sb.append(c);
30     }
31     return sb.toString();
32   }
33
34   /**
35    * creates a SQL literal from value.
36    */

37   public static String JavaDoc escapeSql(Object JavaDoc value) {
38     if (value == null)
39       return "NULL";
40     if (value instanceof String JavaDoc)
41       return "'" + escapeSqlString((String JavaDoc) value) + "'";
42     if (value instanceof java.sql.Date JavaDoc || value instanceof Time JavaDoc
43         || value instanceof java.sql.Timestamp JavaDoc)
44       return "'" + value.toString() + "'";
45     if (value instanceof java.util.Date JavaDoc) {
46       java.sql.Date JavaDoc d = new java.sql.Date JavaDoc(((java.util.Date JavaDoc) value).getTime());
47       return "'" + d.toString() + "'";
48     }
49     return String.valueOf(value);
50   }
51
52   private static String JavaDoc escapeSqlString(String JavaDoc s) {
53     int pos = s.indexOf('\'');
54     if (pos >= 0) {
55       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
56       while (pos >= 0) {
57         sb.append(s.substring(0, pos));
58         sb.append("''");
59         s = s.substring(pos + 1);
60         pos = s.indexOf('\'');
61       }
62       sb.append(s);
63       s = sb.toString();
64     }
65     return s;
66   }
67
68 }
Popular Tags