01: /*
02: * Copyright 2007 Roy van der Kuil (roy@vanderkuil.nl) and Stefan Rotman (stefan@rotman.net)
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package nl.improved.sqlclient;
17:
18: import java.sql.Connection;
19: import java.sql.SQLException;
20:
21: /**
22: * Class to execute SQL statements.
23: * Typical examples would be:
24: * <code>
25: * StatementExecutor se = new StatementExecutor();
26: * se.execute("insert into test values(12, 'test', 'test data')");
27: * </code>
28: * which would then print the result: "1 row affected."; of course, when
29: * the table test would not exist, or would have a different structure this
30: * statement would result in a {@link java.sql.SQLException} being thrown.
31: *
32: * 'Special statements' like for instance <tt>commit</tt> or <tt>rollback</tt>
33: * should be passed through the StatementExecutor as wel:
34: * <code>
35: * se.execute("rollback");
36: * </code>
37: *
38: * @see QueryExecutor
39: */
40: public class StatementExecutor {
41:
42: /**
43: * Executes a provided SQL statement.
44: * @param command the statement to execute.
45: * @return info about the command execution.
46: * @throws SQLException if the database could not execute the SQL statement for some reason.
47: */
48: protected CharSequence execute(CharSequence command)
49: throws SQLException {
50: Connection connection = DBConnector.getInstance()
51: .getConnection();
52: String commandString = command.toString();
53: //Special handling for commit
54: if ("commit".equals(commandString)) {
55: connection.commit();
56: return "Statement executed.\n\n";
57: }
58: //Special handling for rollback
59: if ("rollback".equals(commandString)) {
60: connection.rollback();
61: return "Statement executed.\n\n";
62: }
63:
64: //No "special" command found, executing as a regular sql statement
65: int affected = DBConnector.getInstance().getStatement()
66: .executeUpdate(commandString);
67:
68: //And build the execution info
69: StringBuffer displayValue = new StringBuffer();
70: displayValue.append(affected);
71: displayValue.append(" row");
72: if (affected != 1) {
73: displayValue.append("s");
74: }
75: displayValue.append(" affected.\n\n");
76: return displayValue;
77: }
78: }
|