KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snaq > db > SQLUpdate


1 /*
2     DBPool - JDBC Connection Pool Manager
3     Copyright (c) Giles Winstanley
4 */

5 package snaq.db;
6
7 import java.io.*;
8 import java.sql.*;
9 import java.util.StringTokenizer JavaDoc;
10
11 /**
12  * Command-line utility to send SQL commands to a database.
13  * This class is useful for easily creating a large number of database tables
14  * and/or records from a user-defined file.
15  * It relies on the <tt>ConnectionPoolManager</tt> class to assist
16  * with the creation of a connection to the database, which in turn requires
17  * the appropriate <tt>dbpool.properties</tt> file in the classpath.
18  * <pre>
19  * Usage: java snaq.db.SQLUpdate &lt;pool&gt; &lt;input file&gt; [&lt;separator&gt;]
20  * </pre>
21  * where <tt>pool</tt> is the name of the connection pool as defined in
22  * the dbpool.properties file, <tt>input file</tt> is the name of the text
23  * file containing the SQL statements to be issued to the defined database,
24  * and <tt>separator</tt> is an optional parameter to specify a delimiter
25  * for the SQL statements in the file. If the separator is not specified then
26  * each line of the file is assumed to be a separate statement.
27  * <p>(Note: comments are allowed in the input file by starting the line with
28  * either # or --).
29  * @see snaq.db.ConnectionPoolManager
30  * @author Giles Winstanley
31  */

32 public class SQLUpdate
33 {
34     private ConnectionPoolManager cpm;
35     private Connection con;
36     private Statement statement;
37     private String JavaDoc dbName;
38
39     private ByteArrayOutputStream logBuffer;
40     private PrintWriter log;
41
42
43     public SQLUpdate(String JavaDoc db) throws IOException
44     {
45         dbName = db;
46         cpm = ConnectionPoolManager.getInstance();
47     }
48
49
50     /**
51      * Opens the database connection.
52      */

53     private void openConnection(String JavaDoc s) throws SQLException
54     {
55         if (s == null || s.equals(""))
56         {
57             System.out.println("Please specify a database name");
58             System.exit(1);
59         }
60         con = cpm.getConnection(s);
61         try { statement = con.createStatement(); }
62         catch (SQLException e) {}
63         logBuffer = new ByteArrayOutputStream();
64         log = new PrintWriter(logBuffer);
65     }
66
67
68     /**
69      * Closes the database connection.
70      */

71     private void closeConnection()
72     {
73         try
74         {
75             statement.close();
76             con.close();
77         }
78         catch (SQLException e) {}
79
80         // Output errors to log file
81
log.flush();
82         log.close();
83         if (logBuffer.size() > 0)
84         {
85             try
86             {
87                 FileOutputStream fos = new FileOutputStream("SQLUpdate.log", true);
88                 fos.write(logBuffer.toByteArray());
89                 fos.flush();
90                 fos.close();
91             }
92             catch (IOException ioe) {}
93         }
94         cpm.release();
95     }
96
97
98     /**
99      * Issues a statement to the database.
100      */

101     private void doStatement(String JavaDoc sql)
102     {
103         int count = 0;
104         try
105         {
106             count = statement.executeUpdate(sql);
107             System.out.print(".");
108         }
109         catch (SQLException sqle)
110         {
111             System.out.print("x");
112             log.println();
113             log.println(sql);
114             log.println(sqle.getMessage());
115 // sqle.printStackTrace(log);
116
}
117     }
118
119
120     public static void main(String JavaDoc args[]) throws Exception JavaDoc
121     {
122         if (args == null || args.length < 2)
123         {
124             System.out.println("Usage: java snaq.db.SQLUpdate <database> <text file> [<separator>]");
125             System.exit(0);
126         }
127
128         String JavaDoc db = args[0];
129         String JavaDoc file = args[1];
130         String JavaDoc separator = args.length < 3 ? null : args[2];
131
132         // Load file
133
String JavaDoc contents = null;
134         try
135         {
136             ByteArrayOutputStream bao = new ByteArrayOutputStream();
137             FileInputStream fis = new FileInputStream(file);
138             byte[] b = new byte[4096];
139             int n;
140             while ((n = fis.read(b)) != -1)
141                 bao.write(b, 0, n);
142             fis.close();
143             contents = new String JavaDoc(bao.toByteArray());
144         }
145         catch (IOException ioe)
146         {
147             System.out.println("I/O error with file " + file);
148             System.exit(1);
149         }
150
151         // Open a database connection
152
SQLUpdate sql = null;
153         try
154         {
155             sql = new SQLUpdate(db);
156         }
157         catch (IOException ioe)
158         {
159             System.err.println("Unable to create instance of SQLUpdate");
160             ioe.printStackTrace();
161             System.exit(1);
162         }
163         sql.openConnection(db);
164
165         if (separator == null)
166         {
167             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(contents, "\n\r");
168             while (st.hasMoreTokens())
169             {
170                 String JavaDoc token = st.nextToken().trim();
171                 if (!token.startsWith("#") && !token.equals(""))
172                     sql.doStatement(token);
173             }
174         }
175         else
176         {
177             System.out.println("Separator: " + separator);
178
179             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
180             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(contents, "\n\r");
181             while (st.hasMoreTokens())
182             {
183                 // Get next line
184
String JavaDoc line = st.nextToken();
185
186                 // If line is a comment...ignore it
187
if (line.startsWith("#") || line.startsWith("--"))
188                 {
189                     sb.setLength(0);
190                 }
191                 else
192                 {
193                     int pos = line.indexOf(separator);
194                     if (pos >= 0)
195                     {
196                         sb.append(line.substring(0, pos));
197                         sql.doStatement(sb.toString());
198                         sb.setLength(0);
199                     }
200                     else
201                         sb.append(line);
202                 }
203             }
204         }
205
206         sql.closeConnection();
207         System.out.println();
208     }
209 }
Popular Tags