1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sf.jameleon.sql;
20
21 import net.sf.jameleon.ParamTag;
22
23 import java.sql.Connection;
24 import java.sql.SQLException;
25 import java.sql.PreparedStatement;
26
27 import java.util.ArrayList;
28 import java.util.Iterator;
29
30 /***
31 * Runs a delete or update SQL statement against the database.
32 *
33 * Sometimes putting an application into a required state means connecting
34 * to a database and executing a SQL statment. This can be done with this tag.
35 * The SQL can be an insert, delete or update command. The body of this element
36 * should contain the SQL statement used. See the function tag docs for information
37 * on other attributes supported and/or required by this tag.
38 *
39 * An example might be:
40 * <pre><source>
41 * <junit-session xmlns:j="jelly:core">
42 * <sql-update
43 * functionId="Insert another row into test table"
44 * jdbcDriver="org.hsqldb.jdbcDriver"
45 * jdbcUrl="jdbc:hsqldb:tst/_tmp/jameleon_test2"
46 * jdbcUsername="sa"
47 * jdbcPassword="">
48 * create cached table test2(
49 * test_str varchar,
50 * test_str2 varchar
51 * );
52 * </sql-update>
53 * <sql-update
54 * functionId="Delete row from test table"
55 * jdbcDriver="org.hsqldb.jdbcDriver"
56 * jdbcUrl="jdbc:hsqldb:tst/_tmp/jameleon_test2"
57 * jdbcUsername="sa"
58 * jdbcPassword="">
59 * delete from test2 where test_str='some text';
60 * -- some SQL comment
61 * -- Another SQL comment
62 * </sql-update>
63 * </junit-session>
64 * </source></pre>
65 * @jameleon.function name="sql-update" type="action"
66 * @jameleon.step Connect to the database for the the correct environment
67 * @jameleon.step execute the provided sql statement.
68 */
69 public class SqlUpdateTag extends AbstractSqlTag {
70
71 public SqlUpdateTag(){
72 super();
73 sqlVarName = "sqlUpdateSql";
74 }
75
76 protected void executeSql(Connection conn, String sql) throws SQLException{
77 PreparedStatement stmt = null;
78 try{
79 stmt = conn.prepareStatement(sql);
80 Iterator it = params.iterator();
81 int count = 1;
82 while (it.hasNext()) {
83 ArrayList values = ((ParamTag)it.next()).getParamValues();
84 Iterator valuesIt = values.iterator();
85 while (valuesIt.hasNext()) {
86 stmt.setString(count++, (String)valuesIt.next());
87 }
88 }
89 stmt.execute();
90 conn.commit();
91 }catch(SQLException sqle){
92 conn.rollback();
93 throw sqle;
94 }finally{
95 if (stmt != null) {
96 stmt.close();
97 }
98 }
99 }
100
101 /***
102 * @jameleon.attribute required="false"
103 */
104 public void setSqlUpdateSql(String sqlUpdateSql){
105 setVariable(sqlVarName, sqlUpdateSql);
106 }
107
108 }