KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > functionTests > tests > derbynet > prepStmt


1 /*
2
3    Derby - Class org.apache.derbyTesting.functionTests.tests.derbynet.prepStmt
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derbyTesting.functionTests.tests.derbynet;
23
24 import java.sql.Connection JavaDoc;
25 import java.sql.DriverManager JavaDoc;
26 import java.sql.PreparedStatement JavaDoc;
27 import java.sql.Statement JavaDoc;
28 import java.sql.ResultSet JavaDoc;
29 import java.math.BigDecimal JavaDoc;
30 import java.sql.Date JavaDoc;
31 import java.sql.Time JavaDoc;
32 import java.sql.Timestamp JavaDoc;
33 import java.sql.Types JavaDoc;
34 import java.sql.SQLException JavaDoc;
35 import java.sql.BatchUpdateException JavaDoc;
36 import java.io.ByteArrayInputStream JavaDoc;
37 import java.io.InputStreamReader JavaDoc;
38 import org.apache.derbyTesting.functionTests.util.TestUtil;
39 import org.apache.derby.tools.ij;
40 import org.apache.derby.tools.JDBCDisplayUtil;
41
42 /**
43     This test tests the JDBC PreparedStatement.
44 */

45
46 public class prepStmt
47 {
48     private static Connection JavaDoc conn = null;
49
50     private static String JavaDoc[] testObjects = // string array for cleaning up
51
{"table t1", "table tab1", "table t2", "table bigtab", "table tstab",
52          "table doubletab", "table numtab", "table Numeric_Tab", "table jira614",
53      "table jira614_a", "table jira428", "table jira125", "table varcharclobtab",
54          "table jira125125125125125125125125125125125125125125125125125125125125125125125125125125125125125125125",
55          "table jira1533_a", "table jira1533_b",
56          "table jira1454"};
57
58     public static void main (String JavaDoc args[])
59     {
60         try
61         {
62             System.out.println("prepStmt Test Starts");
63             ij.getPropertyArg(args);
64             conn = ij.startJBMS();
65
66             if (conn == null)
67             {
68                 System.out.println("conn didn't work");
69                 return;
70             }
71     
72             Statement JavaDoc cleanstmt = conn.createStatement();
73             TestUtil.cleanUpTest(cleanstmt, testObjects);
74
75             PreparedStatement JavaDoc ps;
76             ResultSet JavaDoc rs;
77             boolean hasResultSet;
78             int uc;
79
80             // executeUpdate() without parameters
81
System.out.println("executeUpdate() without parameters");
82             ps = conn.prepareStatement("create table t1(c1 int, c2 int, c3 int)");
83             uc = ps.executeUpdate();
84             System.out.println("Update count is: " + uc);
85
86             // executeUpdate() with parameters
87
System.out.println("executeUpdate() with parameters");
88             ps = conn.prepareStatement("insert into t1 values (?, 5, ?)");
89             ps.setInt(1, 99);
90             ps.setInt(2, 9);
91             uc = ps.executeUpdate();
92             System.out.println("Update count is: " + uc);
93
94             // execute() with parameters, no result set returned
95
System.out.println("execute() with parameters, no result set returned");
96             ps = conn.prepareStatement("insert into t1 values (2, 6, ?), (?, 5, 8)");
97             ps.setInt(1, 10);
98             ps.setInt(2, 7);
99             hasResultSet = ps.execute();
100             while (hasResultSet)
101             {
102                 rs = ps.getResultSet();
103                 while (rs.next())
104                     System.out.println("ERROR: should not get here!");
105                 hasResultSet = ps.getMoreResults();
106             }
107             uc = ps.getUpdateCount();
108             if (uc != -1)
109                 System.out.println("Update count is: " + uc);
110
111             // executeQuery() without parameters
112
System.out.println("executQuery() without parameters");
113             ps = conn.prepareStatement("select * from t1");
114             rs = ps.executeQuery();
115             while (rs.next())
116                 System.out.println("got row: "+" "+rs.getInt(1)+" "+rs.getInt(2)+" "+rs.getInt(3));
117             System.out.println("end of rows");
118
119             // executeQuery() with parameters
120
System.out.println("executQuery() with parameters");
121             ps = conn.prepareStatement("select * from t1 where c2 = ?");
122             ps.setInt(1, 5);
123             rs = ps.executeQuery();
124             while (rs.next())
125                 System.out.println("got row: "+" "+rs.getInt(1)+" "+rs.getInt(2)+" "+rs.getInt(3));
126             System.out.println("end of rows");
127
128             // execute() with parameters, with result set returned
129
System.out.println("execute() with parameters with result set returned");
130             ps = conn.prepareStatement("select * from t1 where c2 = ?");
131             ps.setInt(1, 5);
132             hasResultSet = ps.execute();
133             while (hasResultSet)
134             {
135                 rs = ps.getResultSet();
136                 while (rs.next())
137                     System.out.println("got row: "+" "+rs.getInt(1)+" "+rs.getInt(2)+" "+rs.getInt(3));
138                 hasResultSet = ps.getMoreResults();
139             }
140             System.out.println("end of rows");
141             uc = ps.getUpdateCount();
142             if (uc != -1)
143                 System.out.println("Update count is: " + uc);
144
145             // test different data types for input parameters of a PreparedStatement
146
System.out.println("test different data types for input parameters of a Prepared Statement");
147             ps = conn.prepareStatement("create table t2(si smallint,i int, bi bigint, r real, f float, d double precision, n5_2 numeric(5,2), dec10_3 decimal(10,3), ch20 char(20),vc varchar(20), lvc long varchar,b20 char(23) for bit data, vb varchar(23) for bit data, lvb long varchar for bit data, dt date, tm time, ts timestamp not null)");
148             uc = ps.executeUpdate();
149             System.out.println("Update count is: " + uc);
150
151             // byte array for binary values.
152
byte[] ba = new byte[] {0x00,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xa,0xb,0xc,
153                          0xd,0xe,0xf,0x10,0x11,0x12,0x13 };
154
155             ps = conn.prepareStatement("insert into t2 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? , ?)");
156             ps.setShort(1, (short) 1);
157             ps.setInt(2, 2);
158             ps.setLong(3, 3);
159             ps.setFloat(4, (float) 4.0);
160             ps.setDouble(5, 5.0);
161             ps.setDouble(6, 6.0);
162             ps.setBigDecimal(7, new BigDecimal JavaDoc("77.77"));
163             ps.setBigDecimal(8, new BigDecimal JavaDoc("8.1"));
164             ps.setString(9, "column9string");
165             byte[] c10ba = new String JavaDoc("column10vcstring").getBytes("UTF-8");
166             int len = c10ba.length;
167             ps.setAsciiStream(10, new ByteArrayInputStream JavaDoc(c10ba), len);
168             byte[] c11ba = new String JavaDoc("column11lvcstring").getBytes("UTF-8");
169             len = c11ba.length;
170             ps.setCharacterStream(11, new InputStreamReader JavaDoc(new ByteArrayInputStream JavaDoc(c11ba),"UTF-8"),len);
171             ps.setBytes(12,ba);
172             // Calling setBytes on the varchar for bit data type because it
173
// Appears DB2 UDB accepts this only for the BLOB data type...
174
// ps.setBinaryStream(13, new ByteArrayInputStream(ba), ba.length);
175
ps.setBytes(13,ba);
176             ps.setBytes(14,ba);
177             ps.setDate(15, Date.valueOf("2002-04-12"));
178             ps.setTime(16, Time.valueOf("11:44:30"));
179             ps.setTimestamp(17, Timestamp.valueOf("2002-04-12 11:44:30.000000000"));
180             uc = ps.executeUpdate();
181             System.out.println("Update count is: " + uc);
182
183             // test setObject on different datatypes of the input parameters of
184
// PreparedStatement
185
System.out.println("test setObject on different data types for input parameters of a Prepared Statement");
186             ps = conn.prepareStatement("insert into t2 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? , ?)");
187             ps.setObject(1, new Integer JavaDoc(1));
188             ps.setObject(2, new Integer JavaDoc(2));
189             ps.setObject(3, new Long JavaDoc(3));
190             ps.setObject(4, new Float JavaDoc(4.0));
191             ps.setObject(5, new Double JavaDoc(5.0));
192             ps.setObject(6, new Double JavaDoc(6.0));
193             ps.setObject(7, new BigDecimal JavaDoc("77.77"));
194             ps.setObject(8, new BigDecimal JavaDoc("8.1"));
195             ps.setObject(9, "column11string");
196             ps.setObject(10, "column10vcstring");
197             ps.setObject(11, "column11lvcstring");
198             ps.setObject(12,ba);
199             ps.setObject(13,ba);
200             ps.setObject(14,ba);
201             ps.setObject(15, Date.valueOf("2002-04-12"));
202             ps.setObject(16, Time.valueOf("11:44:30"));
203             ps.setObject(17, Timestamp.valueOf("2002-04-12 11:44:30.000000000"));
204             uc = ps.executeUpdate();
205             System.out.println("Update count is: " + uc);
206
207             // test setNull on different datatypes of the input parameters of PreparedStatement
208
System.out.println("test setNull on different data types for input parameters of a Prepared Statement");
209             ps = conn.prepareStatement("insert into t2 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? , ?)");
210             ps.setNull(1, java.sql.Types.SMALLINT);
211             ps.setNull(2, java.sql.Types.INTEGER);
212             ps.setNull(3, java.sql.Types.BIGINT);
213             ps.setNull(4, java.sql.Types.REAL);
214             ps.setNull(5, java.sql.Types.FLOAT);
215             ps.setNull(6, java.sql.Types.DOUBLE);
216             ps.setNull(7, java.sql.Types.NUMERIC);
217             ps.setNull(8, java.sql.Types.DECIMAL);
218             ps.setNull(9, java.sql.Types.CHAR);
219             ps.setNull(10, java.sql.Types.VARCHAR);
220             ps.setNull(11, java.sql.Types.LONGVARCHAR);
221             ps.setNull(12, java.sql.Types.BINARY);
222             ps.setNull(13, java.sql.Types.VARBINARY);
223             ps.setNull(14, java.sql.Types.LONGVARBINARY);
224             ps.setNull(15, java.sql.Types.DATE);
225             ps.setNull(16, java.sql.Types.TIME);
226            
227             ps.setTimestamp(17, Timestamp.valueOf("2002-04-12 11:44:31.000000000")); //slightly after
228
hasResultSet = ps.execute();
229             uc = ps.getUpdateCount();
230             if (uc != -1)
231                 System.out.println("Update count is: " + uc);
232
233             ps = conn.prepareStatement("select * from t2");
234             rs = ps.executeQuery();
235             while (rs.next())
236             {
237                 System.out.println("got row: "+" "+rs.getShort(1)+
238                                    " "+rs.getInt(2)+" "+rs.getLong(3)+
239                                    " "+rs.getFloat(4)+" "+rs.getDouble(5)+
240                                    " "+rs.getDouble(6)+" "+rs.getBigDecimal(7)+
241                                    " "+rs.getBigDecimal(8)+" "+rs.getString(9)+
242                                    " "+rs.getString(10)+" "+rs.getString(11)+
243                                    " "+bytesToString(rs.getBytes(12)) +
244                                    " "+bytesToString(rs.getBytes(13)) +
245                                    " "+bytesToString(rs.getBytes(14)) +
246                                    " "+rs.getDate(15)+
247                                    " "+rs.getTime(16)+" "+rs.getTimestamp(17));
248                 Timestamp JavaDoc ts = rs.getTimestamp(17);
249                 Timestamp JavaDoc temp = Timestamp.valueOf("2002-04-12 11:44:30.000000000");
250                 if (ts.after(temp))
251                     System.out.println("After first Timestamp!");
252                 else if (ts.before(temp))
253                     System.out.println("Before first Timestamp!");
254                 else
255                     System.out.println("Timestamp match!");
256             }
257             System.out.println("end of rows");
258
259             try {
260                 ps = conn.prepareStatement("select * from t2 where i = ?");
261                 rs = ps.executeQuery();
262             }
263             catch (SQLException JavaDoc e) {
264                 System.out.println("SQLState: " + e.getSQLState() + " message: " + e.getMessage());
265             }
266             try {
267                 ps = conn.prepareStatement("insert into t2 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
268                 ps.executeUpdate();
269             }
270             catch (SQLException JavaDoc e) {
271                 System.out.println("SQLState: " + e.getSQLState() + " message: " + e.getMessage());
272             }
273             try {
274                 int tabSize = 1000;
275                 String JavaDoc createBigTabSql = "create table bigtab (";
276                 for (int i = 1; i <= tabSize; i++)
277                 {
278                     createBigTabSql += "c"+ i + " int";
279                     if (i != tabSize)
280                         createBigTabSql += ", ";
281                     else
282                         createBigTabSql += " )";
283                 }
284                 //System.out.println(createBigTabSql);
285
ps = conn.prepareStatement(createBigTabSql);
286                 uc = ps.executeUpdate();
287                 
288                 insertTab(conn, "bigtab",50);
289                 insertTab(conn, "bigtab",200);
290                 insertTab(conn, "bigtab", 300);
291                 insertTab(conn, "bigtab",500);
292                 // prepared Statement with many params (bug 4863)
293
insertTab(conn, "bigtab", 1000);
294                 selectFromBigTab(conn);
295                 // Negative Cases
296
System.out.println("Insert wrong column name");
297                 insertTab(conn, "bigtab", 1001);
298                 // this one will give a sytax error
299
System.out.println("Expected Syntax error ");
300                 insertTab(conn, "bigtab", 0);
301                 // table doesn't exist
302
System.out.println("Expected Table does not exist ");
303                 insertTab(conn, "wrongtab",1000);
304             }
305             catch (SQLException JavaDoc e) {
306                 System.out.println("SQLState: " + e.getSQLState() +
307                                    " message: " + e.getMessage());
308             }
309             rs.close();
310             ps.close();
311
312             testBigDecimalSetObject(conn);
313             testBigDecimalSetObjectWithScale(conn);
314             
315             if (!TestUtil.isJCCFramework()) {
316                 testVaryingClientParameterTypeBatch(conn);
317             }
318
319             test4975(conn);
320             test5130(conn);
321             test5172(conn);
322             jira614Test(conn);
323             jira614Test_a(conn);
324             jira170Test(conn);
325             jira125Test(conn);
326             jira428Test(conn);
327             jira1454Test(conn);
328                         jira1533Test_a(conn);
329                         jira1533Test_b(conn);
330             conn.close();
331             // refresh conn before cleaning up
332
conn = ij.startJBMS();
333             cleanstmt = conn.createStatement();
334             TestUtil.cleanUpTest(cleanstmt, testObjects);
335             cleanstmt.close();
336             conn.close();
337             System.out.println("prepStmt Test Ends");
338         }
339         catch (Exception JavaDoc e)
340         {
341             e.printStackTrace();
342         }
343     }
344     
345     // Test execution of batch update where the type of
346
// a parameter varies for difference entries in the batch.
347
private static void testVaryingClientParameterTypeBatch(Connection JavaDoc conn) throws Exception JavaDoc
348     {
349         Statement JavaDoc stmt = conn.createStatement();
350
351         try { stmt.execute("drop table varcharclobtab"); } catch (Throwable JavaDoc t) { }
352         stmt.execute("create table varcharclobtab (c1 varchar(100), c2 clob)");
353         stmt.close();
354         
355         PreparedStatement JavaDoc pStmt = conn.prepareStatement("insert into varcharclobtab VALUES(?,?)");
356
357         pStmt.setNull(1, Types.VARCHAR);
358         pStmt.setString(2, "clob");
359         pStmt.addBatch();
360         
361         pStmt.setString(1, "varchar");
362         pStmt.setNull(2, Types.CLOB);
363         pStmt.addBatch();
364      
365         // The following statement should not throw an exception.
366
try {
367             pStmt.executeBatch();
368         } catch (ClassCastException JavaDoc e) {
369             System.out.println("FAIL: ClassCastException thrown by testVaryingClientParameterTypeBatch test.");
370             throw e;
371         }
372         pStmt.close();
373     }
374
375     // Test creation and execution of many Prepared Statements
376
// Beetle 5130
377
private static void test5130 (Connection JavaDoc conn) throws Exception JavaDoc
378     {
379         int numOfPreparedStatement = 500;
380         
381         PreparedStatement JavaDoc[] tempPreparedStatement = new
382             PreparedStatement JavaDoc[numOfPreparedStatement];
383         ResultSet JavaDoc rs;
384         String JavaDoc[] tableName = new String JavaDoc[numOfPreparedStatement];
385         for (int i = 0; i < numOfPreparedStatement; i++)
386         {
387              tempPreparedStatement[i] = conn.prepareStatement(
388             "SELECT COUNT(*) from SYS.SYSTABLES",
389             ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
390              rs = tempPreparedStatement[i].executeQuery();
391              rs.close();
392         }
393         for (int i = 0; i < numOfPreparedStatement; i++)
394             tempPreparedStatement[i].close();
395         
396     }
397     
398     private static void test5172(Connection JavaDoc conn) throws Exception JavaDoc
399     {
400         
401         Statement JavaDoc stmt = conn.createStatement();
402         
403         try {
404             stmt.executeUpdate("drop table tab1");
405         }
406         catch (SQLException JavaDoc se)
407         {
408     }
409         
410         stmt.executeUpdate( "CREATE TABLE TSTAB (I int, STATUS_TS Timestamp, PROPERTY_TS Timestamp)" );
411         stmt.executeUpdate("INSERT INTO TSTAB VALUES(1 , '2003-08-15 21:20:00','2003-08-15 21:20:00')");
412         stmt.executeUpdate("INSERT INTO TSTAB VALUES(2 , '1969-12-31 16:00:00.0', '2003-08-15 21:20:00')");
413         
414         stmt.close();
415         
416         String JavaDoc timestamp = "20";
417         String JavaDoc query = "select STATUS_TS " +
418             "from TSTAB " +
419             "where (STATUS_TS >= ? or " +
420             " PROPERTY_TS<?)";
421
422         System.out.println("Negative test setString with Invalid Timestamp:" + timestamp);
423
424         PreparedStatement JavaDoc ps = conn.prepareStatement(query);
425         ps.setString(1,timestamp);
426         ps.setString(2, timestamp );
427         try {
428             ResultSet JavaDoc rs = ps.executeQuery();
429         }
430         catch (SQLException JavaDoc e) {
431             System.out.println("SQLState: " + e.getSQLState() + " message: " + e.getMessage());
432         }
433
434     }
435
436
437     private static void test4975(Connection JavaDoc conn) throws Exception JavaDoc
438     {
439         BigDecimal JavaDoc minBigDecimalVal = null;
440         BigDecimal JavaDoc rBigDecimalVal = null;
441         String JavaDoc sminBigDecimalVal = null;
442
443         PreparedStatement JavaDoc pstmt = null;
444         ResultSet JavaDoc rs = null;
445         Statement JavaDoc stmt = null;
446
447         try
448         {
449             stmt = conn.createStatement();
450             String JavaDoc createTableSQL = "create table Numeric_Tab (MAX_VAL NUMERIC(30,15), MIN_VAL NUMERIC(30,15), NULL_VAL NUMERIC(30,15) DEFAULT NULL)";
451             // to create the Numeric Table
452
stmt.executeUpdate(createTableSQL);
453             
454             String JavaDoc insertSQL = "insert into Numeric_Tab values(999999999999999,0.000000000000001, null)";
455             stmt.executeUpdate(insertSQL);
456
457             //to extract the Maximum Value of BigDecimal to be Updated
458
sminBigDecimalVal = "0.000000000000001";
459             minBigDecimalVal = new BigDecimal JavaDoc(sminBigDecimalVal);
460             logMsg("Minimum BigDecimal Value: " + minBigDecimalVal);
461
462             // to update Null value column with Minimum value
463
String JavaDoc sPrepStmt = "update Numeric_Tab set NULL_VAL=?";
464
465             // Uncomment and prepare the below statement instead to see JCC bug on setObject for decimal
466
//String sPrepStmt = "update Numeric_Tab set NULL_VAL="+sminBigDecimalVal+" where 0.0 != ?";
467
logMsg("Prepared Statement String: " + sPrepStmt);
468             
469             // get the PreparedStatement object
470
pstmt = conn.prepareStatement(sPrepStmt);
471             pstmt.setObject(1,minBigDecimalVal);
472             pstmt.executeUpdate();
473
474             //to query from the database to check the call of pstmt.executeUpdate
475
//to get the query string
476
String JavaDoc Null_Val_Query = "Select NULL_VAL from Numeric_Tab";
477             logMsg(Null_Val_Query);
478             rs = stmt.executeQuery(Null_Val_Query);
479             rs.next();
480
481             rBigDecimalVal = (BigDecimal JavaDoc) rs.getObject(1);
482             logMsg("Returned BigDecimal Value after Updation: " + rBigDecimalVal);
483             logMsg("Value returned from stmt: " + minBigDecimalVal);
484
485             if(rBigDecimalVal.compareTo(minBigDecimalVal) == 0)
486             {
487                 logMsg("setObject Method sets the designated parameter with the Object");
488             }
489             else
490             {
491                 logErr("setObject Method does not set the designated parameter with the Object");
492                 throw new Exception JavaDoc("Call to setObject Method is Failed!");
493             }
494         }
495         catch(SQLException JavaDoc sqle)
496         {
497             logErr("SQL Exception: " + sqle.getMessage());
498             throw new Exception JavaDoc("Call to setObject is Failed!");
499         }
500         catch(Exception JavaDoc e)
501         {
502             logErr("Unexpected Exception: " + e.getMessage());
503             throw new Exception JavaDoc("Call to setObject is Failed!");
504         }
505
506         finally
507         {
508             try
509             {
510                 if(rs != null)
511                 {
512                      rs.close();
513                      rs = null;
514                 }
515                 if(pstmt != null)
516                 {
517                      pstmt.close();
518                      pstmt = null;
519                 }
520                 stmt.executeUpdate("drop table Numeric_Tab");
521                 if(stmt != null)
522                 {
523                      stmt.close();
524                      stmt = null;
525                 }
526             }
527             catch(Exception JavaDoc e){ }
528         }
529     }
530
531     private static void logErr(String JavaDoc s)
532     {
533         System.err.println(s);
534     }
535
536     private static void logMsg(String JavaDoc s)
537     {
538         System.out.println(s);
539     }
540
541     private static void insertTab(Connection JavaDoc conn, String JavaDoc tabname , int numCols) throws SQLException JavaDoc
542     {
543         PreparedStatement JavaDoc ps = null;
544         System.out.println("insertTab ( " + tabname + "," + numCols + ")" );
545         String JavaDoc insertSql = "insert into " + tabname + "(";
546         for (int i = 1; i <= numCols; i++)
547         {
548             insertSql += " c"+ i;
549             if (i != numCols)
550                 insertSql += ", ";
551             else
552                 insertSql += ")";
553         }
554         insertSql += " values (";
555         for (int i = 1; i <= numCols; i++)
556         {
557             insertSql += "?";
558             if (i != numCols)
559                 insertSql += ", ";
560             else
561                 insertSql += " )";
562         }
563
564         try {
565             ps = conn.prepareStatement(insertSql);
566             
567             for (int i = 1; i <= numCols; i++)
568                 ps.setInt(i,i);
569             ps.executeUpdate();
570         } catch (SQLException JavaDoc e)
571         {
572             System.out.println("SQLState: " + e.getSQLState() +
573                                " message: " + e.getMessage());
574         }
575         
576     }
577
578     private static void selectFromBigTab(Connection JavaDoc conn) throws SQLException JavaDoc
579     {
580         PreparedStatement JavaDoc ps = null;
581         ResultSet JavaDoc rs = null;
582
583         String JavaDoc selectSQL = "select * from bigtab";
584         System.out.println(selectSQL);
585         ps = conn.prepareStatement(selectSQL);
586         rs = ps.executeQuery();
587         while (rs.next())
588         {
589             System.out.println("Col # 500 = " + rs.getObject(500) +
590                        " Col 1000 = " + rs.getObject(1000));
591         }
592         
593         rs.close();
594         ps.close();
595    
596     }
597     private static void testBigDecimalSetObject(Connection JavaDoc conn) throws SQLException JavaDoc
598     {
599         setupDoubleTab(conn);
600         testBigDecimalToDoubleConversion(conn);
601     }
602
603
604
605     private static void setupDoubleTab(Connection JavaDoc conn) throws SQLException JavaDoc
606     {
607         String JavaDoc sql;
608         Statement JavaDoc stmt = conn.createStatement();
609         try {
610             stmt.executeUpdate("DROP TABLE doubletab");
611         }
612         catch (SQLException JavaDoc se)
613         {
614             //System.out.println("Table doubletab not dropped. " + se.getMessage());
615

616         }
617
618         sql = "CREATE TABLE doubletab (i int, doubleVal DOUBLE)";
619
620         System.out.println(sql);
621         stmt.executeUpdate(sql);
622         conn.commit();
623         
624     }
625
626     private static void testBigDecimalToDoubleConversion(Connection JavaDoc conn) throws SQLException JavaDoc
627     {
628         System.out.println("\n\ntestBigDecimalToDoubleConversion().");
629         System.out.println(" Check that values are preserved when BigDecimal \n values which have more than 31 digits are converted \n to Double with setObject");
630         ResultSet JavaDoc rs = null;
631         // Insert various double values
632
double[] doubleVals = {1.0E-130,1.0E125, 0, -1.0E124};
633         //BigDecimal[] bigDecimalVals = new BigDecimal[doubleVals.length];
634
BigDecimal JavaDoc[] bigDecimalVals = { new BigDecimal JavaDoc(1.0E-130),
635                                         new BigDecimal JavaDoc(1.0E125),
636                                         new BigDecimal JavaDoc(-1.0E124) ,
637                                         new
638                                             BigDecimal JavaDoc("12345678901234567890123456789012"),
639                                         new BigDecimal JavaDoc("1.2345678901234567890123456789012")
640         };
641
642         String JavaDoc isql = "INSERT INTO doubletab VALUES (?, ?)";
643         //System.out.println("conn.prepareStatement(" + isql +")");
644
PreparedStatement JavaDoc insPs = conn.prepareStatement(isql);
645         String JavaDoc ssql = "SELECT doubleVal FROM doubletab";
646         PreparedStatement JavaDoc selPs = conn.prepareStatement(ssql);
647         String JavaDoc dsql = "DELETE FROM doubletab";
648         PreparedStatement JavaDoc delPs = conn.prepareStatement(dsql);
649         for (int i = 0; i < bigDecimalVals.length; i ++)
650         {
651             BigDecimal JavaDoc bd = bigDecimalVals[i];
652             // Insert value
653
//System.out.println("ps.setObject(1," + bd + ",java.sql.Types.DOUBLE)");
654
insPs.setInt(1,i);
655             insPs.setObject(2,bd,java.sql.Types.DOUBLE);
656             insPs.executeUpdate();
657             // Check Value
658
rs = selPs.executeQuery();
659             rs.next();
660             checkDoubleMatch(bd.doubleValue() , rs.getDouble(1));
661             // Clear out the table;
662
delPs.executeUpdate();
663         }
664         insPs.close();
665         selPs.close();
666         delPs.close();
667         rs.close();
668         conn.commit();
669     }
670
671     static void testBigDecimalSetObjectWithScale(Connection JavaDoc conn) throws Exception JavaDoc
672     {
673         Statement JavaDoc stmt = conn.createStatement();
674         String JavaDoc sql = null;
675
676     System.out.println("\n\ntestBigDecimalSetObjectWithScale(). \nPass scale parameter of setObject");
677
678         try {
679             stmt.executeUpdate("DROP TABLE numtab");
680         }
681         catch (SQLException JavaDoc se)
682         {
683             //System.out.println("Table numtab not dropped. " + se.getMessage());
684
}
685         sql = "CREATE TABLE numtab (num NUMERIC(10,6))";
686         stmt.executeUpdate(sql);
687         
688         // make a big decimal from string
689
BigDecimal JavaDoc bdFromString = new BigDecimal JavaDoc("2.33333333");
690         
691         // prepare a statement which updates the third column of the table with
692
// the DOUBLE columns
693
sql = "INSERT INTO numtab VALUES(?)";
694         PreparedStatement JavaDoc ps = conn.prepareStatement(sql);
695         // setObject using the big decimal value
696
//System.out.println("ps.setObject(1," + bdFromString + * ",java.sql.Types.DECIMAL,2)");
697
int scale = 2;
698         ps.setObject(1,bdFromString,java.sql.Types.DECIMAL,scale);
699         ps.executeUpdate();
700         // check the value
701
sql = "SELECT num FROM numtab";
702         ResultSet JavaDoc rs = stmt.executeQuery(sql);
703         rs.next();
704         // Check that the correct scale was set
705
checkBigDecimalMatch(bdFromString.setScale(scale,
706                                                    BigDecimal.ROUND_DOWN),
707                              (BigDecimal JavaDoc)rs.getObject(1));
708         rs.close();
709         ps.close();
710         stmt.close();
711
712         conn.commit();
713     }
714
715     private static void checkDoubleMatch(double expectedValue, double
716                                          actualValue) {
717         if (actualValue == expectedValue)
718             System.out.println("PASS: Actual value " + actualValue + " matches expected value: " + expectedValue);
719         else
720             new Exception JavaDoc("FAIL: Actual value: " + actualValue +
721                             " does not match expected value:" +
722                           expectedValue).printStackTrace();
723         
724     }
725
726     private static void checkBigDecimalMatch(BigDecimal JavaDoc expectedValue,
727                                              BigDecimal JavaDoc actualValue) {
728         if (actualValue == expectedValue ||
729             (actualValue.compareTo(expectedValue) == 0))
730             System.out.println("PASS: Actual value " + actualValue + " matches expected value: " + expectedValue);
731         else
732             new Exception JavaDoc("FAIL: Actual value: " + actualValue +
733                             " does not match expected value:" +
734                           expectedValue).printStackTrace();
735         
736     }
737
738     private static String JavaDoc bytesToString(byte[] ba)
739     {
740         String JavaDoc s = null;
741         if (ba == null)
742             return s;
743         s = new String JavaDoc();
744         for (int i = 0; i < ba.length; i++)
745             s += (Integer.toHexString(ba[i] & 0x00ff));
746         return s;
747     }
748
749     
750     // Derby bug 614 has to do with how the server responds when the
751
// client closes the statement in between split QRYDTA blocks. We
752
// have to cause a split QRYDTA block, which we can do by having a
753
// bunch of moderately-sized rows which mostly fill a 32K block
754
// followed by a single giant row which overflows the block. Then,
755
// we fetch some of the rows, then close the result set.
756
private static void jira614Test(Connection JavaDoc conn)
757         throws Exception JavaDoc
758     {
759         Statement JavaDoc stmt = conn.createStatement();
760             PreparedStatement JavaDoc ps ;
761         try {
762             stmt.execute("drop table jira614");
763         } catch (Throwable JavaDoc t) { }
764         ps = conn.prepareStatement(
765                 "create table jira614 (c1 varchar(10000))");
766         ps.executeUpdate();
767         String JavaDoc workString = genString("a", 150);
768         ps = conn.prepareStatement("insert into jira614 values (?)");
769         ps.setString(1, workString);
770         for (int row = 0; row < 210; row++)
771             ps.executeUpdate();
772         workString = genString("b", 10000);
773         ps.setString(1, workString);
774         ps.executeUpdate();
775         ps = conn.prepareStatement("select * from jira614");
776             ResultSet JavaDoc rs = ps.executeQuery();
777
778             int rowNum = 0;
779             while (rs.next())
780             {
781                 rowNum++;
782                 if (rowNum == 26)
783                     break;
784             }
785             rs.close(); // This statement actually triggers the bug.
786
System.out.println("Test jira614 completed successfully -- no Distributed Protocol Exception occurred");
787     }
788     private static String JavaDoc genString(String JavaDoc c, int howMany)
789     {
790         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
791         for (int i = 0; i < howMany; i++)
792             buf.append(c);
793         return buf.toString();
794     }
795     // Part two of the regression test for bug 614 verifies that the
796
// server-side statement state is cleaned up when a statement is
797
// re-used. Specifically, we set up a statement which has a non-null
798
// splitQRYDTA value, then we close that statement and re-use it for
799
// a totally unrelated query. If the splitQRYDTA wasn't cleaned up
800
// properly, it comes flooding back as the response to that unrelated
801
// query, causing a protocol parsing exception on the client.
802
private static void jira614Test_a(Connection JavaDoc conn)
803         throws Exception JavaDoc
804     {
805         // 1: set up a second table to use for an unrelated query:
806
Statement JavaDoc stmt = conn.createStatement();
807         PreparedStatement JavaDoc ps ;
808         try { stmt.execute("drop table jira614_a"); } catch (Throwable JavaDoc t) { }
809         stmt.execute("create table jira614_a (c1 int)");
810         ps = conn.prepareStatement("insert into jira614_a values (?)");
811         for (int row = 1; row <= 5; row++)
812         {
813             ps.setInt(1, row);
814             ps.executeUpdate();
815         }
816
817         // 2: get the first statement into a splitQRYDTA state:
818
ResultSet JavaDoc rs = stmt.executeQuery("select * from jira614");
819         int rowNum = 0;
820         while (rs.next())
821         {
822             rowNum++;
823             if (rowNum == 26)
824                 break;
825         }
826         // 3: Now re-use the statement for some totally different purpose:
827
stmt.close();
828         stmt = conn.createStatement();
829         rs = stmt.executeQuery("select * from jira614_a");
830         while (rs.next());
831         ps.close();
832         rs.close();
833         stmt.close();
834     }
835     // Jira-170 has to do with how the server handles re-synchronization of
836
// the data stream when an enormous parameter value follows a failed
837
// prepare statement. Note that it is deliberate here that we are preparing
838
// a statement referring to a non-existing table.
839
private static void jira170Test(Connection JavaDoc conn)
840         throws Exception JavaDoc
841     {
842         Statement JavaDoc stmt = conn.createStatement();
843         PreparedStatement JavaDoc ps = null ;
844         try {
845             stmt.execute("drop table jira170");
846         } catch (Throwable JavaDoc t) { }
847         // Create a huge array of chars to be used as the input parameter
848
char []cData = new char[1000000];
849         for (int i = 0; i < cData.length; i++)
850             cData[i] = Character.forDigit(i%10, 10);
851         // The behavior of this test program depends on how the JDBC driver
852
// handles statement prepares. The DB2 Universal JDBC driver implements
853
// something called "deferred prepares" by default. This means that it
854
// doesn't do the prepare of the statement until the statement is
855
// actually executed. Other drivers, such as the standard Derby client
856
// driver, do the prepare at the time of the prepare. This means that,
857
// depending on which driver we're using and what the driver's
858
// configuration is, we'll get the "table not found" error either on
859
// the prepare or on the execute. It doesn't really matter for the
860
// purposes of the test, because the whole point is that we *dont*
861
// get a DRDA Protocol Exception, but rather a table-not-found
862
// exception.
863
try {
864             ps = conn.prepareStatement("insert into jira170 values (?)");
865             ps.setString(1, new String JavaDoc(cData));
866             ps.execute();
867             System.out.println("Test Jira170 failed: no exception when trying to execute a failed prepare with an enormous parameter");
868         }
869         catch (SQLException JavaDoc e)
870         {
871             if (e.getSQLState().equals("42X05"))
872                 System.out.println("Jira170: caught expected table not found");
873             else
874                 e.printStackTrace();
875         }
876     }
877     /**
878       * Jira-1454 is an off-by-one bug in the splitQRYDTA processing in the
879       * Network Server writeQRYDTA code, and is related to previous bugs
880       * 614, 170, 491, and 492. The issue is that if the DSS block is exactly
881       * the maximum DSS length (32767), then the writeQRYDTA code erroneously
882       * thinks the DSS needs to be split when in fact it doesn't.
883       *
884       * The repro case sets up the boundary scenario; we run the case three
885       * times, once with the value 1 less than the max DSS, once with the
886       * value 1 greater than the max DSS, and once with the exact DSS length.
887       * Only the third case triggers the JIRA-1454 bug; the other two tests
888       * are for completeness.
889       */

890     private static void jira1454Test(Connection JavaDoc conn)
891         throws Exception JavaDoc
892     {
893         tickleDSSLength(conn, 12748);
894         tickleDSSLength(conn, 12750);
895         tickleDSSLength(conn, 12749);
896     }
897     private static void tickleDSSLength(Connection JavaDoc conn, int c2Len)
898         throws Exception JavaDoc
899     {
900         System.out.println("JIRA-1454 repro with c2 len=" + c2Len);
901         Statement JavaDoc st = conn.createStatement();
902
903         try {
904                 st.execute("drop table jira1454");
905         } catch (SQLException JavaDoc se) {}
906         st.execute(
907                 "create table jira1454(c1 varchar(20000),c2 varchar(30000))");
908
909         char [] c1 = new char[20000];
910         for (int i = 0; i < c1.length; i++)
911                 c1[i] = Character.forDigit(i%10, 10);
912         char [] c2 = new char[30000];
913         for (int i = 0; i < c2Len; i++)
914                 c2[i] = Character.forDigit(i%10, 10);
915
916         PreparedStatement JavaDoc pSt =
917             conn.prepareStatement("insert into jira1454 values (?,?)");
918         pSt.setString(1, new String JavaDoc(c1));
919         pSt.setString(2, new String JavaDoc(c2,0, c2Len));
920
921         pSt.execute();
922         pSt.close();
923         ResultSet JavaDoc rs = st.executeQuery("select * from jira1454");
924         while (rs.next())
925                 System.out.println("Fetched a row, c2.length=" +
926                                     rs.getString("c2").length());
927         rs.close();
928         st.close();
929     }
930     /**
931      * Jira-125 has to do with proper use of continuation headers
932      * for very large reply messages, such as the SQLDARD which is
933      * returned for a prepared statement with an enormous number of
934      * parameter markers. This test generates a multi-segment SQLDARD
935      * response message from the server, to verify that the code in
936      * DDMWriter.finalizeDSSLength is executed.
937      *
938      * Repro for DERBY-125 off-by-one error. This repro runs in
939      * two iterations. The first iteration, we use a table name
940      * and a column name that are extra long, so that the server-
941      * side buffer has more data in it. The second iteration, we
942      * use simpler names for the table and column, which take up
943      * less space in the server buffer. Then, since the server-
944      * side bytes array was previously used for a larger amount of
945      * data, then the unused bytes contain old data. Since we
946      * intentionally put the "larger amount of data" into the buffer
947      * during the first iteration, we know what the old data bytes
948      * are going to be. Thus, by using specific lengths for the
949      * table and column names, we can 'shift' the old data until we
950      * reach a point where the off-by-one error manifests itself:
951      * namely, we end up incorrectly leaving a non-zero data byte
952      * in the last position of the current server buffer, which
953      * is wrong.
954      */

955
956     private static void jira125Test(Connection JavaDoc conn)
957         throws Exception JavaDoc
958     {
959         jira125Test_a(conn);
960         jira125Test_b(conn);
961     }
962
963     private static void jira125Test_b(Connection JavaDoc conn)
964         throws Exception JavaDoc
965     {
966         Statement JavaDoc stmt = conn.createStatement();
967         PreparedStatement JavaDoc ps ;
968         try {
969             stmt.execute("drop table jira125");
970         } catch (Throwable JavaDoc t) { }
971         try {
972             stmt.execute("create table jira125 (id integer)");
973             stmt.execute("insert into jira125 values 1, 2, 3");
974         } catch (Throwable JavaDoc t) { }
975         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
976         buf.append("SELECT id FROM jira125 WHERE id IN ( ");
977
978         // Must have at least 551 columns here, in order to force
979
// server buffer beyond 32k. NOTE: Changing this number
980
// could cause the test to "pass" even if a regression
981
// occurs--so only change it if needed!
982
int nCols = 556;
983         for (int i = 0; i < nCols; i++) buf.append("?,");
984         buf.append("?)");
985         ps = conn.prepareStatement(buf.toString());
986         // Note that we actually have nCols+1 parameter markers
987
for (int i = 0; i <= nCols; i++) ps.setInt(i+1, 1);
988         ResultSet JavaDoc rs = ps.executeQuery();
989         while (rs.next());
990         System.out.println("Test jira125 successful: " + (nCols + 1) +
991             " parameter markers successfully prepared and executed.");
992     }
993
994     private static void jira125Test_a(Connection JavaDoc conn)
995         throws Exception JavaDoc
996     {
997         Statement JavaDoc stmt = conn.createStatement();
998
999         // Build a column name that is 99 characters long;
1000
// the length of the column name and the length of
1001
// the table name are important to the repro--so
1002
// do not change these unless you can confirm that
1003
// the new values will behave in the same way.
1004
StringBuffer JavaDoc id = new StringBuffer JavaDoc();
1005        for (int i = 0; i < 49; i++)
1006            id.append("id");
1007        id.append("i");
1008
1009        // Build a table name that is 97 characters long;
1010
// the length of the column name and the length of
1011
// the table name are important to the repro--so
1012
// do not change these unless you can confirm that
1013
// the new values will behave in the same way.
1014
StringBuffer JavaDoc tabName = new StringBuffer JavaDoc("jira");
1015        for (int i = 0; i < 31; i++)
1016            tabName.append("125");
1017
1018        try {
1019            stmt.execute("drop table " + tabName.toString());
1020        } catch (Throwable JavaDoc t) { }
1021        try {
1022            stmt.execute("create table " + tabName.toString() + " (" +
1023                id.toString() + " integer)");
1024            stmt.execute("insert into " + tabName.toString() + " values 1, 2, 3");
1025        } catch (Throwable JavaDoc t) { }
1026
1027        PreparedStatement JavaDoc ps;
1028        StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1029        buf.append("SELECT " + id.toString() + " FROM " +
1030            tabName.toString() + " WHERE " + id.toString() + " IN ( ");
1031
1032        // Must have at least 551 columns here, in order to force
1033
// server buffer beyond 32k. NOTE: Changing this number
1034
// could cause the test to "pass" even if a regression
1035
// occurs--so only change it if needed!
1036
int nCols = 554;
1037        for (int i = 0; i < nCols; i++) buf.append("?,");
1038        buf.append("?)");
1039        ps = conn.prepareStatement(buf.toString());
1040        // Note that we actually have nCols+1 parameter markers
1041
for (int i = 0; i <= nCols; i++) ps.setInt(i+1, 1);
1042        ResultSet JavaDoc rs = ps.executeQuery();
1043        while (rs.next());
1044        System.out.println("Iteration 1 successful: " + (nCols + 1) +
1045            " parameter markers successfully prepared and executed.");
1046    }
1047    // Jira 1533 involves two different bugs regarding the handling of large
1048
// amounts of parameter data: first, the Network Server was incorrectly
1049
// handling the desegmentation of continued DSS segements, and second,
1050
// the Network Server was using the wrong heuristic to determine whether
1051
// long string data was being flowed in-line or externalized.
1052
//
1053
// Tests "a" and "b" provoke two different forms of this problem, one
1054
// with just a single continued segement, and one with several continuations
1055
private static void jira1533Test_a(Connection JavaDoc conn)
1056        throws Exception JavaDoc
1057    {
1058        Statement JavaDoc stmt = conn.createStatement();
1059        PreparedStatement JavaDoc ps ;
1060        try { stmt.execute("drop table jira1533_a"); } catch (Throwable JavaDoc t) { }
1061        stmt.execute("create table jira1533_a (aa BIGINT NOT NULL, "+
1062                "bbbbbb BIGINT DEFAULT 0 NOT NULL,"+
1063                " cccc VARCHAR(40), ddddddddddd BIGINT, eeeeee VARCHAR(128),"+
1064                " ffffffffffffffffff VARCHAR(128),"+
1065                "ggggggggg BLOB(2G), hhhhhhhhh VARCHAR(128), "+
1066                "iiiiiiii VARCHAR(128), jjjjjjjjjjjjjj BIGINT,"+
1067                "kkkkkkkk CHAR(1) DEFAULT 'f', "+
1068                "llllllll CHAR(1) DEFAULT 'f', "+
1069                "mmmmmmmmmmmmm CHAR(1) DEFAULT 'f')");
1070        stmt.close();
1071        ps = conn.prepareStatement(
1072                "INSERT INTO jira1533_a (aa,bbbbbb,cccc,ddddddddddd,eeeeee,"+
1073                " ffffffffffffffffff,"+
1074                "ggggggggg,hhhhhhhhh,iiiiiiii,jjjjjjjjjjjjjj,kkkkkkkk,"+
1075                "llllllll,mmmmmmmmmmmmm)"+
1076                " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
1077        String JavaDoc blobStr = makeString(32584);
1078        ps.setLong(1,5);
1079        ps.setLong(2,1);
1080        ps.setString(3,"AAAAAAAAAAA");
1081        ps.setLong(4,30000);
1082        ps.setString(5,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
1083        ps.setString(6,"AAAAAAAAAAA");
1084        ps.setBytes(7,blobStr.getBytes());
1085        ps.setString(8,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
1086        ps.setString(9,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
1087        ps.setLong(10,1);
1088        ps.setString(11,"1");
1089        ps.setString(12,"1");
1090        ps.setString(13,"1");
1091        ps.execute();
1092        ps.close();
1093        System.out.println("JIRA Test 1533(a) successful (no exception)");
1094    }
1095    private static void jira1533Test_b(Connection JavaDoc conn)
1096        throws Exception JavaDoc
1097    {
1098        Statement JavaDoc stmt = conn.createStatement();
1099        PreparedStatement JavaDoc ps ;
1100        try { stmt.execute("drop table jira1533_b"); } catch (Throwable JavaDoc t) { }
1101        stmt.execute("create table jira1533_b (aa BIGINT NOT NULL, "+
1102                "bbbbbb BIGINT DEFAULT 0 NOT NULL,"+
1103                " cccc VARCHAR(40), ddddddddddd BIGINT, eeeeee VARCHAR(128),"+
1104                " ffffffffffffffffff VARCHAR(128),"+
1105                "g1 BLOB(2G),g2 BLOB(2G),g3 BLOB(2G),g4 BLOB(2G),"+
1106                "ggggggggg BLOB(2G), hhhhhhhhh VARCHAR(128), "+
1107                "iiiiiiii VARCHAR(128), jjjjjjjjjjjjjj BIGINT,"+
1108                "kkkkkkkk CHAR(1) DEFAULT 'f', "+
1109                "llllllll CHAR(1) DEFAULT 'f', "+
1110                "mmmmmmmmmmmmm CHAR(1) DEFAULT 'f')");
1111        stmt.close();
1112        ps = conn.prepareStatement(
1113                "INSERT INTO jira1533_b (aa,bbbbbb,cccc,ddddddddddd,eeeeee,"+
1114                " ffffffffffffffffff,"+
1115                "g1,g2,g3,g4,"+
1116                "ggggggggg,hhhhhhhhh,iiiiiiii,jjjjjjjjjjjjjj,kkkkkkkk,"+
1117                "llllllll,mmmmmmmmmmmmm)"+
1118                " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
1119        String JavaDoc blobStr = makeString(32584);
1120        ps.setLong(1,5);
1121        ps.setLong(2,1);
1122        ps.setString(3,"AAAAAAAAAAA");
1123        ps.setLong(4,30000);
1124        ps.setString(5,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
1125        ps.setString(6,"AAAAAAAAAAA");
1126        ps.setBytes(7,blobStr.getBytes());
1127        ps.setBytes(8,blobStr.getBytes());
1128        ps.setBytes(9,blobStr.getBytes());
1129        ps.setBytes(10,blobStr.getBytes());
1130        ps.setBytes(11,blobStr.getBytes());
1131        ps.setString(12,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
1132        ps.setString(13,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
1133        ps.setLong(14,1);
1134        ps.setString(15,"1");
1135        ps.setString(16,"1");
1136        ps.setString(17,"1");
1137        ps.execute();
1138        ps.close();
1139        System.out.println("JIRA Test 1533(b) successful (no exception)");
1140    }
1141    private static String JavaDoc makeString(int length)
1142    {
1143        StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1144        for (int i = 0; i < length; i++)
1145            buf.append("X");
1146        return buf.toString();
1147    }
1148    // Jira 428 involves large batch sizes for Statement.addBatch and
1149
// Statement.executeBatch. Currently, there is a hard DRDA limit of
1150
// 65535 statements per batch (prior to DERBY-428, the server failed
1151
// at around 9000 statements). The different JDBC clients support slightly
1152
// lower limits: the Network Client supports 65534
1153
// statements in a single batch, the DB2JCC driver v2.4 supports
1154
// 65532 statements, the DB2JCC driver v2.6 supports 32765 statements.
1155
// This test just verifies that a batch of 32765 statements works,
1156
// and that a batch of 100000 statements
1157
// gets a BatchUpdateException from the Network Client.
1158
private static void jira428Test(Connection JavaDoc conn)
1159        throws Exception JavaDoc
1160    {
1161        Statement JavaDoc stmt = conn.createStatement();
1162        PreparedStatement JavaDoc ps ;
1163        try { stmt.execute("drop table jira428"); } catch (Throwable JavaDoc t) { }
1164        stmt.execute("create table jira428 (i integer)");
1165        boolean savedAutoCommit = conn.getAutoCommit();
1166        conn.setAutoCommit(false);
1167        ps = conn.prepareStatement("insert into jira428 values (?)");
1168        for (int i = 0; i < 32765; i++)
1169        {
1170            ps.setInt(1, i);
1171            ps.addBatch();
1172        }
1173        ps.executeBatch();
1174        conn.commit();
1175        // We don't run this part of the test for the JCC client because
1176
// the exception forces the connection closed. For DerbyNetClient, it's
1177
// a clean exception that we can catch and recover from, so we test
1178
// that code path:
1179
if (TestUtil.isDerbyNetClientFramework())
1180        {
1181            ps = conn.prepareStatement("insert into jira428 values (?)");
1182            for (int i = 0; i < 100000; i++)
1183            {
1184                ps.setInt(1, i);
1185                ps.addBatch();
1186            }
1187            try {
1188                ps.executeBatch();
1189                System.out.println("JIRA428 FAILURE: expected an exception saying no more than 65534 statements in a single batch");
1190            }
1191            catch (BatchUpdateException JavaDoc bue)
1192            {
1193                // We don't print anything here because we use the same
1194
// master files for DerbyNet and DerbyNetClient, and we only
1195
// run this portion of the test for DerbyNetClient.
1196
// The exception that we get says "no more than 65534 stmts".
1197
}
1198            conn.commit();
1199        }
1200        conn.setAutoCommit(savedAutoCommit);
1201    }
1202}
1203
Popular Tags