1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.dbunit.database.statement;
23
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import org.dbunit.dataset.DataSetUtils;
28 import org.dbunit.dataset.datatype.DataType;
29 import org.dbunit.dataset.datatype.TypeCastException;
30
31 import java.sql.SQLException;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.StringTokenizer;
35
36
37
38
39
40
41 public class BatchStatementDecorator implements IPreparedBatchStatement
42 {
43
44
45
46
47 private static final Logger logger = LoggerFactory.getLogger(BatchStatementDecorator.class);
48
49 private final IBatchStatement _statement;
50 private final String[] _sqlTemplate;
51 private StringBuffer _sqlBuffer;
52 private int _index;
53
54 BatchStatementDecorator(String sql, IBatchStatement statement)
55 {
56 List list = new ArrayList();
57 StringTokenizer tokenizer = new StringTokenizer(sql, "?");
58 while (tokenizer.hasMoreTokens())
59 {
60 list.add(tokenizer.nextToken());
61 }
62
63 if (sql.endsWith("?"))
64 {
65 list.add("");
66 }
67
68 _sqlTemplate = (String[])list.toArray(new String[0]);
69 _statement = statement;
70
71
72 _index = 0;
73 _sqlBuffer = new StringBuffer(_sqlTemplate[_index++]);
74 }
75
76
77
78
79 public void addValue(Object value, DataType dataType)
80 throws TypeCastException, SQLException
81 {
82 logger.debug("addValue(value={}, dataType={}) - start", value, dataType);
83
84 _sqlBuffer.append(DataSetUtils.getSqlValueString(value, dataType));
85 _sqlBuffer.append(_sqlTemplate[_index++]);
86 }
87
88 public void addBatch() throws SQLException
89 {
90 logger.debug("addBatch() - start");
91
92 _statement.addBatch(_sqlBuffer.toString());
93
94
95 _index = 0;
96 _sqlBuffer = new StringBuffer(_sqlTemplate[_index++]);
97 }
98
99 public int executeBatch() throws SQLException
100 {
101 logger.debug("executeBatch() - start");
102
103 return _statement.executeBatch();
104 }
105
106 public void clearBatch() throws SQLException
107 {
108 logger.debug("clearBatch() - start");
109
110 _statement.clearBatch();
111
112
113 _index = 0;
114 _sqlBuffer = new StringBuffer(_sqlTemplate[_index++]);
115 }
116
117 public void close() throws SQLException
118 {
119 logger.debug("close() - start");
120
121 _statement.close();
122 }
123 }
124
125
126
127