KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > command > dml > RunScript


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.command.dml;
6
7 import java.io.IOException JavaDoc;
8 import java.io.InputStreamReader JavaDoc;
9 import java.io.Reader JavaDoc;
10 import java.sql.SQLException JavaDoc;
11
12 import org.h2.command.Prepared;
13 import org.h2.engine.Session;
14 import org.h2.message.Message;
15 import org.h2.util.ScriptReader;
16 import org.h2.util.StringUtils;
17
18 public class RunScript extends ScriptBase {
19     
20     private String JavaDoc charset = StringUtils.getDefaultCharset();
21
22     public RunScript(Session session) {
23         super(session);
24     }
25     
26     public int update() throws SQLException JavaDoc {
27         session.getUser().checkAdmin();
28         int count = 0;
29         try {
30             openInput();
31             Reader JavaDoc reader = new InputStreamReader JavaDoc(in, charset);
32             ScriptReader r = new ScriptReader(reader);
33             while(true) {
34                 String JavaDoc sql = r.readStatement();
35                 if(sql == null) {
36                     break;
37                 }
38                 execute(sql);
39                 count++;
40             }
41             reader.close();
42         } catch(IOException JavaDoc e) {
43             throw Message.convert(e);
44         } finally {
45             closeIO();
46         }
47         return count;
48     }
49     
50     private void execute(String JavaDoc sql) throws SQLException JavaDoc {
51         try {
52             Prepared command = session.prepare(sql);
53             if(command.isQuery()) {
54                 command.query(0);
55             } else {
56                 command.update();
57             }
58             if(session.getAutoCommit()) {
59                 session.commit();
60             }
61         } catch(SQLException JavaDoc e) {
62             throw Message.addSQL(e, sql);
63         }
64     }
65     
66     public void setCharset(String JavaDoc charset) {
67         this.charset = charset;
68     }
69     
70 }
71
Popular Tags