1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.generator;
17
18 import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
19
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.sql.Connection;
25 import java.sql.DriverManager;
26 import java.sql.SQLException;
27 import java.sql.Statement;
28
29
30
31
32
33
34
35 public class SqlScriptRunner {
36 private String driver;
37 private String url;
38 private String userid;
39 private String password;
40 private InputStream sourceFile;
41
42 public SqlScriptRunner(InputStream sourceFile, String driver, String url,
43 String userId, String password) throws Exception {
44
45 if (!stringHasValue(driver)) {
46 throw new Exception("JDBC Driver is required");
47 }
48
49 if (!stringHasValue(url)) {
50 throw new Exception("JDBC URL is required");
51 }
52
53 this.sourceFile = sourceFile;
54 this.driver = driver;
55 this.url = url;
56 this.userid = userId;
57 this.password = password;
58 }
59
60 public void executeScript() throws Exception {
61
62 Connection connection = null;
63
64 try {
65 Class.forName(driver);
66 connection = DriverManager.getConnection(url, userid, password);
67
68 Statement statement = connection.createStatement();
69
70 BufferedReader br = new BufferedReader(new InputStreamReader(sourceFile));
71
72 String sql;
73
74 while ((sql = readStatement(br)) != null) {
75 statement.execute(sql);
76 }
77
78 closeStatement(statement);
79 connection.commit();
80 br.close();
81 } finally {
82 closeConnection(connection);
83 }
84 }
85
86 public String getDriver() {
87 return driver;
88 }
89
90 public void setDriver(String driver) {
91 this.driver = driver;
92 }
93
94 public String getPassword() {
95 return password;
96 }
97
98 public void setPassword(String password) {
99 this.password = password;
100 }
101
102 private void closeConnection(Connection connection) {
103 if (connection != null) {
104 try {
105 connection.close();
106 } catch (SQLException e) {
107
108 ;
109 }
110 }
111 }
112
113 private void closeStatement(Statement statement) {
114 if (statement != null) {
115 try {
116 statement.close();
117 } catch (SQLException e) {
118
119 ;
120 }
121 }
122 }
123
124 private String readStatement(BufferedReader br) throws IOException {
125 StringBuffer sb = new StringBuffer();
126
127 String line;
128
129 while ((line = br.readLine()) != null) {
130 if (line.startsWith("--")) {
131 continue;
132 }
133
134 if (!stringHasValue(line)) {
135 continue;
136 }
137
138 if (line.endsWith(";")) {
139 sb.append(line.substring(0, line.length() - 1));
140 break;
141 } else {
142 sb.append(' ');
143 sb.append(line);
144 }
145 }
146
147 String s = sb.toString().trim();
148
149 return s.length() > 0 ? s : null;
150 }
151 }