2
2
3
3
import java .sql .Connection ;
4
4
import java .sql .DriverManager ;
5
+ import java .sql .PreparedStatement ;
5
6
import java .sql .ResultSet ;
6
7
import java .sql .SQLException ;
7
8
import java .sql .Statement ;
@@ -34,8 +35,10 @@ protected void sql(String sql) throws SQLException {
34
35
}
35
36
36
37
protected void assertQueriesEqual (String q1 , String q2 ) throws SQLException {
37
- List <Object []> res1 = query (q1 );
38
- List <Object []> res2 = query (q2 );
38
+ assertResultSetsEqual (query (q1 ), query (q2 ));
39
+ }
40
+
41
+ protected void assertResultSetsEqual (List <Object []> res1 , List <Object []> res2 ) {
39
42
Assertions .assertEquals (res1 .size (), res2 .size (), "ResultSets are not the same size" );
40
43
for (int i = 0 ; i < res1 .size (); i ++) {
41
44
Assertions .assertArrayEquals (res1 .get (i ), res2 .get (i ), "Rows did not match at row #" + i );
@@ -53,17 +56,31 @@ protected void assertQueryNonEmpty(String q) throws SQLException {
53
56
}
54
57
55
58
protected List <Object []> query (String query ) throws SQLException {
56
- List <Object []> results = new ArrayList <>();
57
59
try (Statement stmt = conn .createStatement ()) {
58
60
ResultSet cursor = stmt .executeQuery (query );
59
- while (cursor .next ()) {
60
- int n = cursor .getMetaData ().getColumnCount ();
61
- Object [] row = new Object [n ];
62
- for (int i = 0 ; i < n ; i ++) {
63
- row [i ] = cursor .getObject (i + 1 );
64
- }
65
- results .add (row );
61
+ return buildRows (cursor );
62
+ }
63
+ }
64
+
65
+ protected List <Object []> queryUsingPreparedStatement (String query , List <String > params ) throws SQLException {
66
+ try (PreparedStatement stmt = conn .prepareStatement (query )) {
67
+ for (int i = 0 ; i < params .size (); i ++) {
68
+ stmt .setString (i + 1 , params .get (i ));
69
+ }
70
+ ResultSet cursor = stmt .executeQuery ();
71
+ return buildRows (cursor );
72
+ }
73
+ }
74
+
75
+ private static List <Object []> buildRows (ResultSet cursor ) throws SQLException {
76
+ List <Object []> results = new ArrayList <>();
77
+ while (cursor .next ()) {
78
+ int n = cursor .getMetaData ().getColumnCount ();
79
+ Object [] row = new Object [n ];
80
+ for (int i = 0 ; i < n ; i ++) {
81
+ row [i ] = cursor .getObject (i + 1 );
66
82
}
83
+ results .add (row );
67
84
}
68
85
return results ;
69
86
}
0 commit comments