KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > testsuite > regression > StatementRegressionTest


1 /*
2  Copyright (C) 2002-2004 MySQL AB
3
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of version 2 of the GNU General Public License as
6  published by the Free Software Foundation.
7
8  There are special exceptions to the terms and conditions of the GPL
9  as it is applied to this software. View the full text of the
10  exception in file EXCEPTIONS-CONNECTOR-J in the directory of this
11  software distribution.
12
13  This program is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with this program; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22
23
24  */

25 package testsuite.regression;
26
27 import java.io.ByteArrayInputStream JavaDoc;
28 import java.io.CharArrayReader JavaDoc;
29 import java.io.File JavaDoc;
30 import java.io.FileOutputStream JavaDoc;
31 import java.io.FileWriter JavaDoc;
32 import java.io.Writer JavaDoc;
33 import java.math.BigDecimal JavaDoc;
34 import java.sql.BatchUpdateException JavaDoc;
35 import java.sql.Blob JavaDoc;
36 import java.sql.Clob JavaDoc;
37 import java.sql.Connection JavaDoc;
38 import java.sql.DataTruncation JavaDoc;
39 import java.sql.Date JavaDoc;
40 import java.sql.PreparedStatement JavaDoc;
41 import java.sql.ResultSet JavaDoc;
42 import java.sql.SQLException JavaDoc;
43 import java.sql.SQLWarning JavaDoc;
44 import java.sql.Statement JavaDoc;
45 import java.sql.Time JavaDoc;
46 import java.sql.Timestamp JavaDoc;
47 import java.sql.Types JavaDoc;
48 import java.text.SimpleDateFormat JavaDoc;
49 import java.util.Calendar JavaDoc;
50 import java.util.Properties JavaDoc;
51 import java.util.TimeZone JavaDoc;
52
53 import testsuite.BaseTestCase;
54
55 import com.mysql.jdbc.SQLError;
56 import com.mysql.jdbc.ServerPreparedStatement;
57
58 /**
59  * Regression tests for the Statement class
60  *
61  * @author Mark Matthews
62  */

63 public class StatementRegressionTest extends BaseTestCase {
64     class PrepareThread extends Thread JavaDoc {
65         Connection JavaDoc c;
66
67         PrepareThread(Connection JavaDoc cn) {
68             c = cn;
69         }
70
71         public void run() {
72             for (int i = 0; i < 20; i++) // force this to end eventually
73
{
74                 try {
75                     c.prepareStatement("SELECT 1");
76                     testServerPrepStmtDeadlockCounter++;
77                     Thread.sleep(400);
78                 } catch (SQLException JavaDoc sqlEx) {
79                     throw new RuntimeException JavaDoc(sqlEx);
80                 } catch (InterruptedException JavaDoc e) {
81                     e.printStackTrace();
82                 }
83             }
84         }
85     }
86
87     /*
88      * Each row in this table is to be converted into a single REPLACE
89      * statement. If the value is zero, a new record is to be created using then
90      * autoincrement feature. If the value is non-zero, the existing row of that
91      * value is to be replace with, obviously, the same key. I expect one
92      * Generated Key for each zero value - but I would accept one key for each
93      * value, with non-zero values coming back as themselves.
94      */

95     static final int[][] tests = { { 0 }, // generate 1
96
{ 1, 0, 0 }, // update 1, generate 2, 3
97
{ 2, 0, 0, }, // update 2, generate 3, 4
98
};
99
100     static int nextID = 1; // The next ID we expected to generate
101

102     static int count = 0;
103
104     private int testServerPrepStmtDeadlockCounter = 0;
105
106     /**
107      * Constructor for StatementRegressionTest.
108      *
109      * @param name
110      * the name of the test to run
111      */

112     public StatementRegressionTest(String JavaDoc name) {
113         super(name);
114     }
115
116     /**
117      * Runs all test cases in this test suite
118      *
119      * @param args
120      */

121     public static void main(String JavaDoc[] args) {
122         junit.textui.TestRunner.run(StatementRegressionTest.class);
123     }
124
125     /**
126      * Tests fix for BUG#1774 -- Truncated words after double quote
127      *
128      * @throws Exception
129      * if the test fails.
130      */

131     public void testBug1774() throws Exception JavaDoc {
132         try {
133             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1774");
134             this.stmt
135                     .executeUpdate("CREATE TABLE testBug1774 (field1 VARCHAR(255))");
136
137             PreparedStatement JavaDoc pStmt = this.conn
138                     .prepareStatement("INSERT INTO testBug1774 VALUES (?)");
139
140             String JavaDoc testString = "The word contains \" character";
141
142             pStmt.setString(1, testString);
143             pStmt.executeUpdate();
144
145             this.rs = this.stmt.executeQuery("SELECT * FROM testBug1774");
146             this.rs.next();
147             assertTrue(this.rs.getString(1).equals(testString));
148         } finally {
149             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1774");
150         }
151     }
152
153     /**
154      * Tests fix for BUG#1901 -- PreparedStatement.setObject(int, Object, int,
155      * int) doesn't support CLOB or BLOB types.
156      *
157      * @throws Exception
158      * if this test fails for any reason
159      */

160     public void testBug1901() throws Exception JavaDoc {
161         try {
162             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1901");
163             this.stmt
164                     .executeUpdate("CREATE TABLE testBug1901 (field1 VARCHAR(255))");
165             this.stmt.executeUpdate("INSERT INTO testBug1901 VALUES ('aaa')");
166
167             this.rs = this.stmt.executeQuery("SELECT field1 FROM testBug1901");
168             this.rs.next();
169
170             Clob JavaDoc valueAsClob = this.rs.getClob(1);
171             Blob JavaDoc valueAsBlob = this.rs.getBlob(1);
172
173             PreparedStatement JavaDoc pStmt = this.conn
174                     .prepareStatement("INSERT INTO testBug1901 VALUES (?)");
175             pStmt.setObject(1, valueAsClob, java.sql.Types.CLOB, 0);
176             pStmt.executeUpdate();
177             pStmt.setObject(1, valueAsBlob, java.sql.Types.BLOB, 0);
178             pStmt.executeUpdate();
179         } finally {
180             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1901");
181         }
182     }
183
184     /**
185      * Test fix for BUG#1933 -- Driver property 'maxRows' has no effect.
186      *
187      * @throws Exception
188      * if the test fails.
189      */

190     public void testBug1933() throws Exception JavaDoc {
191         if (versionMeetsMinimum(4, 0)) {
192             Connection JavaDoc maxRowsConn = null;
193             PreparedStatement JavaDoc maxRowsPrepStmt = null;
194             Statement JavaDoc maxRowsStmt = null;
195
196             try {
197                 Properties JavaDoc props = new Properties JavaDoc();
198
199                 props.setProperty("maxRows", "1");
200
201                 maxRowsConn = getConnectionWithProps(props);
202
203                 maxRowsStmt = maxRowsConn.createStatement();
204
205                 assertTrue(maxRowsStmt.getMaxRows() == 1);
206
207                 this.rs = maxRowsStmt.executeQuery("SELECT 1 UNION SELECT 2");
208
209                 this.rs.next();
210
211                 maxRowsPrepStmt = maxRowsConn
212                         .prepareStatement("SELECT 1 UNION SELECT 2");
213
214                 assertTrue(maxRowsPrepStmt.getMaxRows() == 1);
215
216                 this.rs = maxRowsPrepStmt.executeQuery();
217
218                 this.rs.next();
219
220                 assertTrue(!this.rs.next());
221
222                 props.setProperty("useServerPrepStmts", "false");
223
224                 maxRowsConn = getConnectionWithProps(props);
225
226                 maxRowsPrepStmt = maxRowsConn
227                         .prepareStatement("SELECT 1 UNION SELECT 2");
228
229                 assertTrue(maxRowsPrepStmt.getMaxRows() == 1);
230
231                 this.rs = maxRowsPrepStmt.executeQuery();
232
233                 this.rs.next();
234
235                 assertTrue(!this.rs.next());
236             } finally {
237                 maxRowsConn.close();
238             }
239         }
240     }
241
242     /**
243      * Tests the fix for BUG#1934 -- prepareStatement dies silently when
244      * encountering Statement.RETURN_GENERATED_KEY
245      *
246      * @throws Exception
247      * if the test fails
248      */

249     public void testBug1934() throws Exception JavaDoc {
250         try {
251             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1934");
252             this.stmt.executeUpdate("CREATE TABLE testBug1934 (field1 INT)");
253
254             System.out.println("Before prepareStatement()");
255
256             this.pstmt = this.conn.prepareStatement(
257                     "INSERT INTO testBug1934 VALUES (?)",
258                     java.sql.Statement.RETURN_GENERATED_KEYS);
259
260             assertTrue(this.pstmt != null);
261
262             System.out.println("After prepareStatement() - " + this.pstmt);
263         } finally {
264             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1934");
265         }
266     }
267
268     /**
269      * Tests fix for BUG#1958 - Improper bounds checking on
270      * PreparedStatement.setFoo().
271      *
272      * @throws Exception
273      * if the test fails.
274      */

275     public void testBug1958() throws Exception JavaDoc {
276         PreparedStatement JavaDoc pStmt = null;
277
278         try {
279             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1958");
280             this.stmt.executeUpdate("CREATE TABLE testBug1958 (field1 int)");
281
282             pStmt = this.conn
283                     .prepareStatement("SELECT * FROM testBug1958 WHERE field1 IN (?, ?, ?)");
284
285             try {
286                 pStmt.setInt(4, 1);
287             } catch (SQLException JavaDoc sqlEx) {
288                 assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
289                         .getSQLState()));
290             }
291         } finally {
292             if (pStmt != null) {
293                 pStmt.close();
294             }
295
296             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1958");
297         }
298     }
299
300     /**
301      * Tests the fix for BUG#2606, server-side prepared statements not returning
302      * datatype YEAR correctly.
303      *
304      * @throws Exception
305      * if the test fails.
306      */

307     public void testBug2606() throws Exception JavaDoc {
308         try {
309             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug2606");
310             this.stmt
311                     .executeUpdate("CREATE TABLE testBug2606(year_field YEAR)");
312             this.stmt.executeUpdate("INSERT INTO testBug2606 VALUES (2004)");
313
314             PreparedStatement JavaDoc yrPstmt = this.conn
315                     .prepareStatement("SELECT year_field FROM testBug2606");
316
317             this.rs = yrPstmt.executeQuery();
318
319             assertTrue(this.rs.next());
320
321             assertEquals(2004, this.rs.getInt(1));
322         } finally {
323             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug2606");
324         }
325     }
326
327     /**
328      * Tests the fix for BUG#2671, nulls encoded incorrectly in server-side
329      * prepared statements.
330      *
331      * @throws Exception
332      * if an error occurs.
333      */

334     public void testBug2671() throws Exception JavaDoc {
335         if (versionMeetsMinimum(4, 1)) {
336             try {
337                 this.stmt.executeUpdate("DROP TABLE IF EXISTS test3");
338                 this.stmt
339                         .executeUpdate("CREATE TABLE test3 ("
340                                 + " `field1` int(8) NOT NULL auto_increment,"
341                                 + " `field2` int(8) unsigned zerofill default NULL,"
342                                 + " `field3` varchar(30) binary NOT NULL default '',"
343                                 + " `field4` varchar(100) default NULL,"
344                                 + " `field5` datetime NOT NULL default '0000-00-00 00:00:00',"
345                                 + " PRIMARY KEY (`field1`),"
346                                 + " UNIQUE KEY `unq_id` (`field2`),"
347                                 + " UNIQUE KEY (`field3`),"
348                                 + " UNIQUE KEY (`field2`)"
349                                 + " ) TYPE=InnoDB CHARACTER SET utf8");
350
351                 this.stmt
352                         .executeUpdate("insert into test3 (field1, field3, field4) values (1,'blewis','Bob Lewis')");
353
354                 String JavaDoc query = " " + "UPDATE "
355                         + " test3 "
356                         + "SET "
357                         + " field2=? " + " ,field3=? "
358                         + " ,field4=? " + " ,field5=? "
359                         + "WHERE "
360                         + " field1 = ? ";
361
362                 java.sql.Date JavaDoc mydate = null;
363
364                 this.pstmt = this.conn.prepareStatement(query);
365
366                 this.pstmt.setInt(1, 13);
367                 this.pstmt.setString(2, "abc");
368                 this.pstmt.setString(3, "def");
369                 this.pstmt.setDate(4, mydate);
370                 this.pstmt.setInt(5, 1);
371
372                 int retval = this.pstmt.executeUpdate();
373                 assertTrue(retval == 1);
374             } finally {
375                 this.stmt.executeUpdate("DROP TABLE IF EXISTS test3");
376             }
377         }
378     }
379
380     /**
381      * Tests fix for BUG#3103 -- java.util.Date not accepted as parameter to
382      * PreparedStatement.setObject().
383      *
384      * @throws Exception
385      * if the test fails
386      *
387      * @deprecated uses deprecated methods of Date class
388      */

389     public void testBug3103() throws Exception JavaDoc {
390         try {
391             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3103");
392             this.stmt
393                     .executeUpdate("CREATE TABLE testBug3103 (field1 DATETIME)");
394
395             PreparedStatement JavaDoc pStmt = this.conn
396                     .prepareStatement("INSERT INTO testBug3103 VALUES (?)");
397
398             java.util.Date JavaDoc utilDate = new java.util.Date JavaDoc();
399
400             pStmt.setObject(1, utilDate);
401             pStmt.executeUpdate();
402
403             this.rs = this.stmt.executeQuery("SELECT field1 FROM testBug3103");
404             this.rs.next();
405
406             java.util.Date JavaDoc retrUtilDate = new java.util.Date JavaDoc(this.rs
407                     .getTimestamp(1).getTime());
408
409             // We can only compare on the day/month/year hour/minute/second
410
// interval, because the timestamp has added milliseconds to the
411
// internal date...
412
assertTrue("Dates not equal", (utilDate.getMonth() == retrUtilDate
413                     .getMonth())
414                     && (utilDate.getDate() == retrUtilDate.getDate())
415                     && (utilDate.getYear() == retrUtilDate.getYear())
416                     && (utilDate.getHours() == retrUtilDate.getHours())
417                     && (utilDate.getMinutes() == retrUtilDate.getMinutes())
418                     && (utilDate.getSeconds() == retrUtilDate.getSeconds()));
419         } finally {
420             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3103");
421         }
422     }
423
424     /**
425      * Tests fix for BUG#3520
426      *
427      * @throws Exception
428      * ...
429      */

430     public void testBug3520() throws Exception JavaDoc {
431         try {
432             this.stmt.executeUpdate("DROP TABLE IF EXISTS t");
433             this.stmt.executeUpdate("CREATE TABLE t (s1 int,primary key (s1))");
434             this.stmt.executeUpdate("INSERT INTO t VALUES (1)");
435             this.stmt.executeUpdate("INSERT INTO t VALUES (1)");
436         } catch (SQLException JavaDoc sqlEx) {
437             System.out.println(sqlEx.getSQLState());
438         } finally {
439             this.stmt.executeUpdate("DROP TABLE IF EXISTS t");
440         }
441     }
442
443     /**
444      * Test fix for BUG#3557 -- UpdatableResultSet not picking up default values
445      *
446      * @throws Exception
447      * if test fails.
448      */

449     public void testBug3557() throws Exception JavaDoc {
450         try {
451             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");
452
453             this.stmt.executeUpdate("CREATE TABLE testBug3557 ( "
454                     + "`a` varchar(255) NOT NULL default 'XYZ', "
455                     + "`b` varchar(255) default '123', "
456                     + "PRIMARY KEY (`a`))");
457
458             Statement JavaDoc updStmt = this.conn
459                     .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
460                             ResultSet.CONCUR_UPDATABLE);
461             this.rs = updStmt.executeQuery("SELECT * FROM testBug3557");
462
463             assertTrue(this.rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE);
464
465             this.rs.moveToInsertRow();
466
467             assertEquals("XYZ", this.rs.getObject(1));
468             assertEquals("123", this.rs.getObject(2));
469         } finally {
470             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");
471         }
472     }
473
474     /**
475      * Tests fix for BUG#3620 -- Timezone not respected correctly.
476      *
477      * @throws SQLException
478      * if the test fails.
479      */

480     public void testBug3620() throws SQLException JavaDoc {
481         long epsillon = 3000; // 3 seconds time difference
482

483         try {
484             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3620");
485             this.stmt
486                     .executeUpdate("CREATE TABLE testBug3620 (field1 TIMESTAMP)");
487
488             PreparedStatement JavaDoc tsPstmt = this.conn
489                     .prepareStatement("INSERT INTO testBug3620 VALUES (?)");
490
491             Calendar JavaDoc pointInTime = Calendar.getInstance();
492             pointInTime.set(2004, 02, 29, 10, 0, 0);
493
494             long pointInTimeOffset = pointInTime.getTimeZone().getRawOffset();
495
496             java.sql.Timestamp JavaDoc ts = new java.sql.Timestamp JavaDoc(pointInTime
497                     .getTime().getTime());
498
499             tsPstmt.setTimestamp(1, ts);
500             tsPstmt.executeUpdate();
501
502             String JavaDoc tsValueAsString = getSingleValue("testBug3620", "field1",
503                     null).toString();
504
505             System.out.println("Timestamp as string with no calendar: "
506                     + tsValueAsString.toString());
507
508             Calendar JavaDoc cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
509
510             this.stmt.executeUpdate("DELETE FROM testBug3620");
511
512             Properties JavaDoc props = new Properties JavaDoc();
513             props.put("useTimezone", "true");
514             // props.put("serverTimezone", "UTC");
515

516             Connection JavaDoc tzConn = getConnectionWithProps(props);
517
518             Statement JavaDoc tsStmt = tzConn.createStatement();
519
520             tsPstmt = tzConn
521                     .prepareStatement("INSERT INTO testBug3620 VALUES (?)");
522
523             tsPstmt.setTimestamp(1, ts, cal);
524             tsPstmt.executeUpdate();
525
526             tsValueAsString = getSingleValue("testBug3620", "field1", null)
527                     .toString();
528
529             Timestamp JavaDoc tsValueAsTimestamp = (Timestamp JavaDoc) getSingleValue(
530                     "testBug3620", "field1", null);
531
532             System.out.println("Timestamp as string with UTC calendar: "
533                     + tsValueAsString.toString());
534             System.out.println("Timestamp as Timestamp with UTC calendar: "
535                     + tsValueAsTimestamp);
536
537             this.rs = tsStmt.executeQuery("SELECT field1 FROM testBug3620");
538             this.rs.next();
539
540             Timestamp JavaDoc tsValueUTC = this.rs.getTimestamp(1, cal);
541
542             //
543
// We use this testcase with other vendors, JDBC spec
544
// requires result set fields can only be read once,
545
// although MySQL doesn't require this ;)
546
//
547
this.rs = tsStmt.executeQuery("SELECT field1 FROM testBug3620");
548             this.rs.next();
549
550             Timestamp JavaDoc tsValueStmtNoCal = this.rs.getTimestamp(1);
551
552             System.out
553                     .println("Timestamp specifying UTC calendar from normal statement: "
554                             + tsValueUTC.toString());
555
556             PreparedStatement JavaDoc tsPstmtRetr = tzConn
557                     .prepareStatement("SELECT field1 FROM testBug3620");
558
559             this.rs = tsPstmtRetr.executeQuery();
560             this.rs.next();
561
562             Timestamp JavaDoc tsValuePstmtUTC = this.rs.getTimestamp(1, cal);
563
564             System.out
565                     .println("Timestamp specifying UTC calendar from prepared statement: "
566                             + tsValuePstmtUTC.toString());
567
568             //
569
// We use this testcase with other vendors, JDBC spec
570
// requires result set fields can only be read once,
571
// although MySQL doesn't require this ;)
572
//
573
this.rs = tsPstmtRetr.executeQuery();
574             this.rs.next();
575
576             Timestamp JavaDoc tsValuePstmtNoCal = this.rs.getTimestamp(1);
577
578             System.out
579                     .println("Timestamp specifying no calendar from prepared statement: "
580                             + tsValuePstmtNoCal.toString());
581
582             long stmtDeltaTWithCal = (ts.getTime() - tsValueStmtNoCal.getTime());
583
584             long deltaOrig = Math.abs(stmtDeltaTWithCal - pointInTimeOffset);
585
586             assertTrue(
587                     "Difference between original timestamp and timestamp retrieved using java.sql.Statement "
588                             + "set in database using UTC calendar is not ~= "
589                             + epsillon + ", it is actually " + deltaOrig,
590                     (deltaOrig < epsillon));
591
592             long pStmtDeltaTWithCal = (ts.getTime() - tsValuePstmtNoCal
593                     .getTime());
594
595             System.out
596                     .println(Math.abs(pStmtDeltaTWithCal - pointInTimeOffset)
597                             + " < "
598                             + epsillon
599                             + (Math.abs(pStmtDeltaTWithCal - pointInTimeOffset) < epsillon));
600             assertTrue(
601                     "Difference between original timestamp and timestamp retrieved using java.sql.PreparedStatement "
602                             + "set in database using UTC calendar is not ~= "
603                             + epsillon
604                             + ", it is actually "
605                             + pStmtDeltaTWithCal, (Math.abs(pStmtDeltaTWithCal
606                             - pointInTimeOffset) < epsillon));
607
608             System.out
609                     .println("Difference between original ts and ts with no calendar: "
610                             + (ts.getTime() - tsValuePstmtNoCal.getTime())
611                             + ", offset should be " + pointInTimeOffset);
612         } finally {
613             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3620");
614         }
615     }
616
617     /**
618      * Tests that DataTruncation is thrown when data is truncated.
619      *
620      * @throws Exception
621      * if the test fails.
622      */

623     public void testBug3697() throws Exception JavaDoc {
624         try {
625             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3697");
626             this.stmt
627                     .executeUpdate("CREATE TABLE testBug3697 (field1 VARCHAR(255))");
628
629             StringBuffer JavaDoc updateBuf = new StringBuffer JavaDoc(
630                     "INSERT INTO testBug3697 VALUES ('");
631
632             for (int i = 0; i < 512; i++) {
633                 updateBuf.append("A");
634             }
635
636             updateBuf.append("')");
637
638             try {
639                 this.stmt.executeUpdate(updateBuf.toString());
640             } catch (DataTruncation JavaDoc dtEx) {
641                 // This is an expected exception....
642
}
643
644             SQLWarning JavaDoc warningChain = this.stmt.getWarnings();
645
646             System.out.println(warningChain);
647         } finally {
648             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3697");
649         }
650     }
651
652     /**
653      * Tests fix for BUG#3804, data truncation on server should throw
654      * DataTruncation exception.
655      *
656      * @throws Exception
657      * if the test fails
658      */

659     public void testBug3804() throws Exception JavaDoc {
660         if (versionMeetsMinimum(4, 1)) {
661             try {
662                 this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3804");
663                 this.stmt
664                         .executeUpdate("CREATE TABLE testBug3804 (field1 VARCHAR(5))");
665
666                 boolean caughtTruncation = false;
667
668                 try {
669                     this.stmt
670                             .executeUpdate("INSERT INTO testBug3804 VALUES ('1234567')");
671                 } catch (DataTruncation JavaDoc truncationEx) {
672                     caughtTruncation = true;
673                     System.out.println(truncationEx);
674                 }
675
676                 assertTrue("Data truncation exception should've been thrown",
677                         caughtTruncation);
678             } finally {
679                 this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3804");
680             }
681         }
682     }
683
684     /**
685      * Tests BUG#3873 - PreparedStatement.executeBatch() not returning all
686      * generated keys (even though that's not JDBC compliant).
687      *
688      * @throws Exception
689      * if the test fails
690      */

691     public void testBug3873() throws Exception JavaDoc {
692         PreparedStatement JavaDoc batchStmt = null;
693
694         try {
695             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3873");
696             this.stmt
697                     .executeUpdate("CREATE TABLE testBug3873 (keyField INT NOT NULL PRIMARY KEY AUTO_INCREMENT, dataField VARCHAR(32))");
698             batchStmt = this.conn.prepareStatement(
699                     "INSERT INTO testBug3873 (dataField) VALUES (?)",
700                     Statement.RETURN_GENERATED_KEYS);
701             batchStmt.setString(1, "abc");
702             batchStmt.addBatch();
703             batchStmt.setString(1, "def");
704             batchStmt.addBatch();
705             batchStmt.setString(1, "ghi");
706             batchStmt.addBatch();
707
708             int[] updateCounts = batchStmt.executeBatch();
709
710             this.rs = batchStmt.getGeneratedKeys();
711
712             while (this.rs.next()) {
713                 System.out.println(this.rs.getInt(1));
714             }
715
716             this.rs = batchStmt.getGeneratedKeys();
717             assertTrue(this.rs.next());
718             assertTrue(1 == this.rs.getInt(1));
719             assertTrue(this.rs.next());
720             assertTrue(2 == this.rs.getInt(1));
721             assertTrue(this.rs.next());
722             assertTrue(3 == this.rs.getInt(1));
723             assertTrue(!this.rs.next());
724         } finally {
725             if (batchStmt != null) {
726                 batchStmt.close();
727             }
728
729             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3873");
730         }
731     }
732
733     /**
734      * Tests that you can close a statement twice without an NPE.
735      *
736      * @throws Exception
737      * if an error occurs.
738      */

739     public void testCloseTwice() throws Exception JavaDoc {
740         Statement JavaDoc closeMe = this.conn.createStatement();
741         closeMe.close();
742         closeMe.close();
743     }
744
745     /**
746      * Tests all forms of statements influencing getGeneratedKeys().
747      *
748      * @throws Exception
749      * if the test fails.
750      */

751     public void testGetGeneratedKeysAllCases() throws Exception JavaDoc {
752         System.out.println("Using Statement.executeUpdate()\n");
753
754         try {
755             createGGKTables();
756
757             // Do the tests
758
for (int i = 0; i < tests.length; i++) {
759                 doGGKTestStatement(tests[i], true);
760             }
761         } finally {
762             dropGGKTables();
763         }
764
765         nextID = 1;
766         count = 0;
767
768         System.out.println("Using Statement.execute()\n");
769
770         try {
771             createGGKTables();
772
773             // Do the tests
774
for (int i = 0; i < tests.length; i++) {
775                 doGGKTestStatement(tests[i], false);
776             }
777         } finally {
778             dropGGKTables();
779         }
780
781         nextID = 1;
782         count = 0;
783
784         System.out.println("Using PreparedStatement.executeUpdate()\n");
785
786         try {
787             createGGKTables();
788
789             // Do the tests
790
for (int i = 0; i < tests.length; i++) {
791                 doGGKTestPreparedStatement(tests[i], true);
792             }
793         } finally {
794             dropGGKTables();
795         }
796
797         nextID = 1;
798         count = 0;
799
800         System.out.println("Using PreparedStatement.execute()\n");
801
802         try {
803             createGGKTables();
804
805             // Do the tests
806
for (int i = 0; i < tests.length; i++) {
807                 doGGKTestPreparedStatement(tests[i], false);
808             }
809         } finally {
810             dropGGKTables();
811         }
812     }
813
814     /**
815      * Tests fix for BUG#4119 -- misbehavior in a managed environment from
816      * MVCSoft JDO
817      *
818      * @throws Exception
819      * if the test fails.
820      */

821     public void testBug4119() throws Exception JavaDoc {
822         try {
823             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4119");
824             this.stmt.executeUpdate("CREATE TABLE `testBug4119` ("
825                     + "`field1` varchar(255) NOT NULL default '',"
826                     + "`field2` bigint(20) default NULL,"
827                     + "`field3` int(11) default NULL,"
828                     + "`field4` datetime default NULL,"
829                     + "`field5` varchar(75) default NULL,"
830                     + "`field6` varchar(75) default NULL,"
831                     + "`field7` varchar(75) default NULL,"
832                     + "`field8` datetime default NULL,"
833                     + " PRIMARY KEY (`field1`)" + ")");
834
835             PreparedStatement JavaDoc pStmt = this.conn
836                     .prepareStatement("insert into testBug4119 (field2, field3,"
837                             + "field4, field5, field6, field7, field8, field1) values (?, ?,"
838                             + "?, ?, ?, ?, ?, ?)");
839
840             pStmt.setString(1, "0");
841             pStmt.setString(2, "0");
842             pStmt.setTimestamp(3, new java.sql.Timestamp JavaDoc(System
843                     .currentTimeMillis()));
844             pStmt.setString(4, "ABC");
845             pStmt.setString(5, "DEF");
846             pStmt.setString(6, "AA");
847             pStmt.setTimestamp(7, new java.sql.Timestamp JavaDoc(System
848                     .currentTimeMillis()));
849             pStmt.setString(8, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
850             pStmt.executeUpdate();
851         } finally {
852             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4119");
853         }
854     }
855
856     /**
857      * Tests that max_rows and 'limit' don't cause exceptions to be thrown.
858      *
859      * @throws Exception
860      * if the test fails.
861      */

862     public void testLimitAndMaxRows() throws Exception JavaDoc {
863         try {
864             this.stmt.executeUpdate("DROP TABLE IF EXISTS testMaxRowsAndLimit");
865             this.stmt
866                     .executeUpdate("CREATE TABLE testMaxRowsAndLimit(limitField INT)");
867
868             for (int i = 0; i < 500; i++) {
869                 this.stmt
870                         .executeUpdate("INSERT INTO testMaxRowsAndLimit VALUES ("
871                                 + i + ")");
872             }
873
874             this.stmt.setMaxRows(250);
875             this.stmt
876                     .executeQuery("SELECT limitField FROM testMaxRowsAndLimit");
877         } finally {
878             this.stmt.setMaxRows(0);
879
880             this.stmt.executeUpdate("DROP TABLE IF EXISTS testMaxRowsAndLimit");
881         }
882     }
883
884     /**
885      * Tests that 'LOAD DATA LOCAL INFILE' works
886      *
887      * @throws Exception
888      * if any errors occur
889      */

890     public void testLoadData() throws Exception JavaDoc {
891         try {
892             int maxAllowedPacket = 1048576;
893
894             this.stmt.executeUpdate("DROP TABLE IF EXISTS loadDataRegress");
895             this.stmt
896                     .executeUpdate("CREATE TABLE loadDataRegress (field1 int, field2 int)");
897
898             File JavaDoc tempFile = File.createTempFile("mysql", ".txt");
899
900             // tempFile.deleteOnExit();
901
System.out.println(tempFile);
902
903             Writer JavaDoc out = new FileWriter JavaDoc(tempFile);
904
905             int localCount = 0;
906             int rowCount = 128; // maxAllowedPacket * 4;
907

908             for (int i = 0; i < rowCount; i++) {
909                 out.write((localCount++) + "\t" + (localCount++) + "\n");
910             }
911
912             out.close();
913
914             StringBuffer JavaDoc fileNameBuf = null;
915
916             if (File.separatorChar == '\\') {
917                 fileNameBuf = new StringBuffer JavaDoc();
918
919                 String JavaDoc fileName = tempFile.getAbsolutePath();
920                 int fileNameLength = fileName.length();
921
922                 for (int i = 0; i < fileNameLength; i++) {
923                     char c = fileName.charAt(i);
924
925                     if (c == '\\') {
926                         fileNameBuf.append("/");
927                     } else {
928                         fileNameBuf.append(c);
929                     }
930                 }
931             } else {
932                 fileNameBuf = new StringBuffer JavaDoc(tempFile.getAbsolutePath());
933             }
934
935             int updateCount = this.stmt
936                     .executeUpdate("LOAD DATA LOCAL INFILE '"
937                             + fileNameBuf.toString()
938                             + "' INTO TABLE loadDataRegress");
939             assertTrue(updateCount == rowCount);
940         } finally {
941             this.stmt.executeUpdate("DROP TABLE IF EXISTS loadDataRegress");
942         }
943     }
944
945     /**
946      * Tests fix for BUG#1658
947      *
948      * @throws Exception
949      * if the fix for parameter bounds checking doesn't work.
950      */

951     public void testParameterBoundsCheck() throws Exception JavaDoc {
952         try {
953             this.stmt
954                     .executeUpdate("DROP TABLE IF EXISTS testParameterBoundsCheck");
955             this.stmt
956                     .executeUpdate("CREATE TABLE testParameterBoundsCheck(f1 int, f2 int, f3 int, f4 int, f5 int)");
957
958             PreparedStatement JavaDoc pstmt = this.conn
959                     .prepareStatement("UPDATE testParameterBoundsCheck SET f1=?, f2=?,f3=?,f4=? WHERE f5=?");
960
961             pstmt.setString(1, "");
962             pstmt.setString(2, "");
963
964             try {
965                 pstmt.setString(25, "");
966             } catch (SQLException JavaDoc sqlEx) {
967                 assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
968                         .getSQLState()));
969             }
970         } finally {
971             this.stmt
972                     .executeUpdate("DROP TABLE IF EXISTS testParameterBoundsCheck");
973         }
974     }
975
976     /**
977      * Tests fix for BUG#1511
978      *
979      * @throws Exception
980      * if the quoteid parsing fix in PreparedStatement doesn't work.
981      */

982     public void testQuotedIdRecognition() throws Exception JavaDoc {
983         if (!this.versionMeetsMinimum(4, 1)) {
984             try {
985                 this.stmt.executeUpdate("DROP TABLE IF EXISTS testQuotedId");
986                 this.stmt
987                         .executeUpdate("CREATE TABLE testQuotedId (col1 VARCHAR(32))");
988
989                 PreparedStatement JavaDoc pStmt = this.conn
990                         .prepareStatement("SELECT * FROM testQuotedId FROM WHERE col1='ABC`DEF' or col1=?");
991                 pStmt.setString(1, "foo");
992                 System.out.println(pStmt);
993             } finally {
994                 this.stmt.executeUpdate("DROP TABLE IF EXISTS testQuotedId");
995             }
996         }
997     }
998
999     /**
1000     * Tests that binary dates/times are encoded/decoded correctly.
1001     *
1002     * @throws Exception
1003     * if the test fails.
1004     *
1005     * @deprecated because we need to use this particular constructor for the
1006     * date class, as Calendar-constructed dates don't pass the
1007     * .equals() test :(
1008     */

1009    public void testServerPrepStmtAndDate() throws Exception JavaDoc {
1010        try {
1011            this.stmt
1012                    .executeUpdate("DROP TABLE IF EXISTS testServerPrepStmtAndDate");
1013            this.stmt.executeUpdate("CREATE TABLE testServerPrepStmtAndDate("
1014                    + "`P_ID` int(10) NOT NULL default '0',"
1015                    + "`H_ID` int(10) NOT NULL default '0',"
1016                    + "`R_ID` int(10) NOT NULL default '0',"
1017                    + "`H_Age` int(10) default NULL,"
1018                    + "`R_Date` date NOT NULL default '0000-00-00',"
1019                    + "`Comments` varchar(255) default NULL,"
1020                    + "`Weight` int(10) default NULL,"
1021                    + "`HeadGear` char(1) NOT NULL default '',"
1022                    + "`FinPos` int(10) default NULL,"
1023                    + "`Jock_ID` int(10) default NULL,"
1024                    + "`BtnByPrev` double default NULL,"
1025                    + "`BtnByWinner` double default NULL,"
1026                    + "`Jock_All` int(10) default NULL,"
1027                    + "`Draw` int(10) default NULL,"
1028                    + "`SF` int(10) default NULL,"
1029                    + "`RHR` int(10) default NULL,"
1030                    + "`ORating` int(10) default NULL,"
1031                    + "`Odds` double default NULL,"
1032                    + "`RaceFormPlus` int(10) default NULL,"
1033                    + "`PrevPerform` int(10) default NULL,"
1034                    + "`TrainerID` int(10) NOT NULL default '0',"
1035                    + "`DaysSinceRun` int(10) default NULL,"
1036                    + "UNIQUE KEY `P_ID` (`P_ID`),"
1037                    + "UNIQUE KEY `R_H_ID` (`R_ID`,`H_ID`),"
1038                    + "KEY `R_Date` (`R_Date`)," + "KEY `H_Age` (`H_Age`),"
1039                    + "KEY `TrainerID` (`TrainerID`)," + "KEY `H_ID` (`H_ID`)"
1040                    + ")");
1041
1042            Date JavaDoc dt = new java.sql.Date JavaDoc(102, 1, 2); // Note, this represents the
1043
// date 2002-02-02
1044

1045            PreparedStatement JavaDoc pStmt2 = this.conn
1046                    .prepareStatement("INSERT INTO testServerPrepStmtAndDate (P_ID, R_Date) VALUES (171576, ?)");
1047            pStmt2.setDate(1, dt);
1048            pStmt2.executeUpdate();
1049            pStmt2.close();
1050
1051            this.rs = this.stmt
1052                    .executeQuery("SELECT R_Date FROM testServerPrepStmtAndDate");
1053            this.rs.next();
1054
1055            System.out.println("Date that was stored (as String) "
1056                    + this.rs.getString(1)); // comes back as 2002-02-02
1057

1058            PreparedStatement JavaDoc pStmt = this.conn
1059                    .prepareStatement("Select P_ID,R_Date from testServerPrepStmtAndDate Where R_Date = ? and P_ID = 171576");
1060            pStmt.setDate(1, dt);
1061
1062            this.rs = pStmt.executeQuery();
1063
1064            assertTrue(this.rs.next());
1065
1066            assertTrue("171576".equals(this.rs.getString(1)));
1067
1068            Date JavaDoc retDt = this.rs.getDate(2);
1069
1070            assertTrue(dt.equals(this.rs.getDate(2)));
1071        } finally {
1072            this.stmt
1073                    .executeUpdate("DROP TABLE IF EXISTS testServerPrepStmtAndDate");
1074        }
1075    }
1076
1077    /**
1078     * Tests PreparedStatement.setCharacterStream() to ensure it accepts > 4K
1079     * streams
1080     *
1081     * @throws Exception
1082     * if an error occurs.
1083     */

1084    public void testSetCharacterStream() throws Exception JavaDoc {
1085        try {
1086            ((com.mysql.jdbc.Connection) this.conn).setTraceProtocol(true);
1087
1088            this.stmt
1089                    .executeUpdate("DROP TABLE IF EXISTS charStreamRegressTest");
1090            this.stmt
1091                    .executeUpdate("CREATE TABLE charStreamRegressTest(field1 text)");
1092
1093            this.pstmt = this.conn
1094                    .prepareStatement("INSERT INTO charStreamRegressTest VALUES (?)");
1095
1096            // char[] charBuf = new char[16384];
1097
char[] charBuf = new char[32];
1098
1099            for (int i = 0; i < charBuf.length; i++) {
1100                charBuf[i] = 'A';
1101            }
1102
1103            CharArrayReader JavaDoc reader = new CharArrayReader JavaDoc(charBuf);
1104
1105            this.pstmt.setCharacterStream(1, reader, charBuf.length);
1106            this.pstmt.executeUpdate();
1107
1108            this.rs = this.stmt
1109                    .executeQuery("SELECT LENGTH(field1) FROM charStreamRegressTest");
1110
1111            this.rs.next();
1112
1113            System.out.println("Character stream length: "
1114                    + this.rs.getString(1));
1115
1116            this.rs = this.stmt
1117                    .executeQuery("SELECT field1 FROM charStreamRegressTest");
1118
1119            this.rs.next();
1120
1121            String JavaDoc result = this.rs.getString(1);
1122
1123            assertTrue(result.length() == charBuf.length);
1124
1125            this.stmt.execute("TRUNCATE TABLE charStreamRegressTest");
1126
1127            // Test that EOF is not thrown
1128
reader = new CharArrayReader JavaDoc(charBuf);
1129            this.pstmt.clearParameters();
1130            this.pstmt.setCharacterStream(1, reader, charBuf.length);
1131            this.pstmt.executeUpdate();
1132
1133            this.rs = this.stmt
1134                    .executeQuery("SELECT LENGTH(field1) FROM charStreamRegressTest");
1135
1136            this.rs.next();
1137
1138            System.out.println("Character stream length: "
1139                    + this.rs.getString(1));
1140
1141            this.rs = this.stmt
1142                    .executeQuery("SELECT field1 FROM charStreamRegressTest");
1143
1144            this.rs.next();
1145
1146            result = this.rs.getString(1);
1147
1148            assertTrue("Retrieved value of length " + result.length()
1149                    + " != length of inserted value " + charBuf.length, result
1150                    .length() == charBuf.length);
1151
1152            // Test single quotes inside identifers
1153
this.stmt
1154                    .executeUpdate("DROP TABLE IF EXISTS `charStream'RegressTest`");
1155            this.stmt
1156                    .executeUpdate("CREATE TABLE `charStream'RegressTest`(field1 text)");
1157
1158            this.pstmt = this.conn
1159                    .prepareStatement("INSERT INTO `charStream'RegressTest` VALUES (?)");
1160
1161            reader = new CharArrayReader JavaDoc(charBuf);
1162            this.pstmt.setCharacterStream(1, reader, (charBuf.length * 2));
1163            this.pstmt.executeUpdate();
1164
1165            this.rs = this.stmt
1166                    .executeQuery("SELECT field1 FROM `charStream'RegressTest`");
1167
1168            this.rs.next();
1169
1170            result = this.rs.getString(1);
1171
1172            assertTrue("Retrieved value of length " + result.length()
1173                    + " != length of inserted value " + charBuf.length, result
1174                    .length() == charBuf.length);
1175        } finally {
1176            ((com.mysql.jdbc.Connection) this.conn).setTraceProtocol(false);
1177
1178            if (this.rs != null) {
1179                try {
1180                    this.rs.close();
1181                } catch (Exception JavaDoc ex) {
1182                    // ignore
1183
}
1184
1185                this.rs = null;
1186            }
1187
1188            this.stmt
1189                    .executeUpdate("DROP TABLE IF EXISTS `charStream'RegressTest`");
1190            this.stmt
1191                    .executeUpdate("DROP TABLE IF EXISTS charStreamRegressTest");
1192        }
1193    }
1194
1195    /**
1196     * Tests a bug where Statement.setFetchSize() does not work for values other
1197     * than 0 or Integer.MIN_VALUE
1198     *
1199     * @throws Exception
1200     * if any errors occur
1201     */

1202    public void testSetFetchSize() throws Exception JavaDoc {
1203        int oldFetchSize = this.stmt.getFetchSize();
1204
1205        try {
1206            this.stmt.setFetchSize(10);
1207        } finally {
1208            this.stmt.setFetchSize(oldFetchSize);
1209        }
1210    }
1211
1212    /**
1213     * Tests fix for BUG#907
1214     *
1215     * @throws Exception
1216     * if an error occurs
1217     */

1218    public void testSetMaxRows() throws Exception JavaDoc {
1219        Statement JavaDoc maxRowsStmt = null;
1220
1221        try {
1222            maxRowsStmt = this.conn.createStatement();
1223            maxRowsStmt.setMaxRows(1);
1224            maxRowsStmt.executeQuery("SELECT 1");
1225        } finally {
1226            if (maxRowsStmt != null) {
1227                maxRowsStmt.close();
1228            }
1229        }
1230    }
1231
1232    /**
1233     * Tests for timestamp NPEs occuring in binary-format timestamps.
1234     *
1235     * @throws Exception
1236     * DOCUMENT ME!
1237     *
1238     * @deprecated yes, we know we are using deprecated methods here :)
1239     */

1240    public void testTimestampNPE() throws Exception JavaDoc {
1241        try {
1242            Timestamp JavaDoc ts = new Timestamp JavaDoc(System.currentTimeMillis());
1243
1244            this.stmt.executeUpdate("DROP TABLE IF EXISTS testTimestampNPE");
1245            this.stmt
1246                    .executeUpdate("CREATE TABLE testTimestampNPE (field1 TIMESTAMP)");
1247
1248            this.pstmt = this.conn
1249                    .prepareStatement("INSERT INTO testTimestampNPE VALUES (?)");
1250            this.pstmt.setTimestamp(1, ts);
1251            this.pstmt.executeUpdate();
1252
1253            this.pstmt = this.conn
1254                    .prepareStatement("SELECT field1 FROM testTimestampNPE");
1255
1256            this.rs = this.pstmt.executeQuery();
1257
1258            this.rs.next();
1259
1260            System.out.println(this.rs.getString(1));
1261
1262            this.rs.getDate(1);
1263
1264            Timestamp JavaDoc rTs = this.rs.getTimestamp(1);
1265            assertTrue("Retrieved year of " + rTs.getYear()
1266                    + " does not match " + ts.getYear(), rTs.getYear() == ts
1267                    .getYear());
1268            assertTrue("Retrieved month of " + rTs.getMonth()
1269                    + " does not match " + ts.getMonth(), rTs.getMonth() == ts
1270                    .getMonth());
1271            assertTrue("Retrieved date of " + rTs.getDate()
1272                    + " does not match " + ts.getDate(), rTs.getDate() == ts
1273                    .getDate());
1274        } finally {
1275        }
1276    }
1277
1278    /**
1279     * Tests fix for updatable streams being supported in updatable result sets.
1280     *
1281     * @throws Exception
1282     * if the test fails.
1283     */

1284    public void testUpdatableStream() throws Exception JavaDoc {
1285        try {
1286            this.stmt.executeUpdate("DROP TABLE IF EXISTS updateStreamTest");
1287            this.stmt
1288                    .executeUpdate("CREATE TABLE updateStreamTest (keyField INT NOT NULL AUTO_INCREMENT PRIMARY KEY, field1 BLOB)");
1289
1290            int streamLength = 16385;
1291            byte[] streamData = new byte[streamLength];
1292
1293            /* create an updatable statement */
1294            Statement JavaDoc updStmt = this.conn.createStatement(
1295                    ResultSet.TYPE_SCROLL_INSENSITIVE,
1296                    ResultSet.CONCUR_UPDATABLE);
1297
1298            /* fill the resultset with some values */
1299            ResultSet JavaDoc updRs = updStmt
1300                    .executeQuery("SELECT * FROM updateStreamTest");
1301
1302            /* move to insertRow */
1303            updRs.moveToInsertRow();
1304
1305            /* update the table */
1306            updRs.updateBinaryStream("field1", new ByteArrayInputStream JavaDoc(
1307                    streamData), streamLength);
1308
1309            updRs.insertRow();
1310        } finally {
1311            this.stmt.executeUpdate("DROP TABLE IF EXISTS updateStreamTest");
1312        }
1313    }
1314
1315    private void createGGKTables() throws Exception JavaDoc {
1316        // Delete and recreate table
1317
dropGGKTables();
1318
1319        this.stmt.executeUpdate("CREATE TABLE testggk ("
1320                + "id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,"
1321                + "val INT NOT NULL" + ")");
1322    }
1323
1324    private void doGGKTestPreparedStatement(int[] values, boolean useUpdate)
1325            throws Exception JavaDoc {
1326        // Generate the the multiple replace command
1327
StringBuffer JavaDoc cmd = new StringBuffer JavaDoc("REPLACE INTO testggk VALUES ");
1328        int newKeys = 0;
1329
1330        for (int i = 0; i < values.length; i++) {
1331            cmd.append("(");
1332
1333            if (values[i] == 0) {
1334                cmd.append("NULL");
1335                newKeys += 1;
1336            } else {
1337                cmd.append(values[i]);
1338            }
1339
1340            cmd.append(", ");
1341            cmd.append(count++);
1342            cmd.append("), ");
1343        }
1344
1345        cmd.setLength(cmd.length() - 2); // trim the final ", "
1346

1347        // execute and print it
1348
System.out.println(cmd.toString());
1349
1350        PreparedStatement JavaDoc pStmt = this.conn.prepareStatement(cmd.toString(),
1351                Statement.RETURN_GENERATED_KEYS);
1352
1353        if (useUpdate) {
1354            pStmt.executeUpdate();
1355        } else {
1356            pStmt.execute();
1357        }
1358
1359        // print out what actually happened
1360
System.out.println("Expect " + newKeys
1361                + " generated keys, starting from " + nextID);
1362
1363        this.rs = pStmt.getGeneratedKeys();
1364        StringBuffer JavaDoc res = new StringBuffer JavaDoc("Got keys");
1365
1366        int[] generatedKeys = new int[newKeys];
1367        int i = 0;
1368
1369        while (this.rs.next()) {
1370            if (i < generatedKeys.length) {
1371                generatedKeys[i] = this.rs.getInt(1);
1372            }
1373
1374            i++;
1375
1376            res.append(" " + this.rs.getInt(1));
1377        }
1378
1379        int numberOfGeneratedKeys = i;
1380
1381        assertTrue(
1382                "Didn't retrieve expected number of generated keys, expected "
1383                        + newKeys + ", found " + numberOfGeneratedKeys,
1384                numberOfGeneratedKeys == newKeys);
1385        assertTrue("Keys didn't start with correct sequence: ",
1386                generatedKeys[0] == nextID);
1387
1388        System.out.println(res.toString());
1389
1390        // Read and print the new state of the table
1391
this.rs = this.stmt.executeQuery("SELECT id, val FROM testggk");
1392        System.out.println("New table contents ");
1393
1394        while (this.rs.next())
1395            System.out.println("Id " + this.rs.getString(1) + " val "
1396                    + this.rs.getString(2));
1397
1398        // Tidy up
1399
System.out.println("");
1400        nextID += newKeys;
1401    }
1402
1403    private void doGGKTestStatement(int[] values, boolean useUpdate)
1404            throws Exception JavaDoc {
1405        // Generate the the multiple replace command
1406
StringBuffer JavaDoc cmd = new StringBuffer JavaDoc("REPLACE INTO testggk VALUES ");
1407        int newKeys = 0;
1408
1409        for (int i = 0; i < values.length; i++) {
1410            cmd.append("(");
1411
1412            if (values[i] == 0) {
1413                cmd.append("NULL");
1414                newKeys += 1;
1415            } else {
1416                cmd.append(values[i]);
1417            }
1418
1419            cmd.append(", ");
1420            cmd.append(count++);
1421            cmd.append("), ");
1422        }
1423
1424        cmd.setLength(cmd.length() - 2); // trim the final ", "
1425

1426        // execute and print it
1427
System.out.println(cmd.toString());
1428
1429        if (useUpdate) {
1430            this.stmt.executeUpdate(cmd.toString(),
1431                    Statement.RETURN_GENERATED_KEYS);
1432        } else {
1433            this.stmt.execute(cmd.toString(), Statement.RETURN_GENERATED_KEYS);
1434        }
1435
1436        // print out what actually happened
1437
System.out.println("Expect " + newKeys
1438                + " generated keys, starting from " + nextID);
1439
1440        this.rs = this.stmt.getGeneratedKeys();
1441        StringBuffer JavaDoc res = new StringBuffer JavaDoc("Got keys");
1442
1443        int[] generatedKeys = new int[newKeys];
1444        int i = 0;
1445
1446        while (this.rs.next()) {
1447            if (i < generatedKeys.length) {
1448                generatedKeys[i] = this.rs.getInt(1);
1449            }
1450
1451            i++;
1452
1453            res.append(" " + this.rs.getInt(1));
1454        }
1455
1456        int numberOfGeneratedKeys = i;
1457
1458        assertTrue(
1459                "Didn't retrieve expected number of generated keys, expected "
1460                        + newKeys + ", found " + numberOfGeneratedKeys,
1461                numberOfGeneratedKeys == newKeys);
1462        assertTrue("Keys didn't start with correct sequence: ",
1463                generatedKeys[0] == nextID);
1464
1465        System.out.println(res.toString());
1466
1467        // Read and print the new state of the table
1468
this.rs = this.stmt.executeQuery("SELECT id, val FROM testggk");
1469        System.out.println("New table contents ");
1470
1471        while (this.rs.next())
1472            System.out.println("Id " + this.rs.getString(1) + " val "
1473                    + this.rs.getString(2));
1474
1475        // Tidy up
1476
System.out.println("");
1477        nextID += newKeys;
1478    }
1479
1480    private void dropGGKTables() throws Exception JavaDoc {
1481        this.stmt.executeUpdate("DROP TABLE IF EXISTS testggk");
1482    }
1483
1484    /**
1485     * Tests fix for BUG#4311 - Error in JDBC retrieval of mediumint column when
1486     * using prepared statements and binary result sets.
1487     *
1488     * @throws Exception
1489     * if the test fails.
1490     */

1491    public void testBug4311() throws Exception JavaDoc {
1492        try {
1493            int lowValue = -8388608;
1494            int highValue = 8388607;
1495
1496            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4311");
1497            this.stmt
1498                    .executeUpdate("CREATE TABLE testBug4311 (low MEDIUMINT, high MEDIUMINT)");
1499            this.stmt.executeUpdate("INSERT INTO testBug4311 VALUES ("
1500                    + lowValue + ", " + highValue + ")");
1501
1502            PreparedStatement JavaDoc pStmt = this.conn
1503                    .prepareStatement("SELECT low, high FROM testBug4311");
1504            this.rs = pStmt.executeQuery();
1505            assertTrue(this.rs.next());
1506            assertTrue(this.rs.getInt(1) == lowValue);
1507            assertTrue(this.rs.getInt(2) == highValue);
1508        } finally {
1509            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4311");
1510        }
1511    }
1512
1513    /**
1514     * Tests fix for BUG#4510 -- Statement.getGeneratedKeys() fails when key >
1515     * 32767
1516     *
1517     * @throws Exception
1518     * if the test fails
1519     */

1520    public void testBug4510() throws Exception JavaDoc {
1521        try {
1522            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4510");
1523            this.stmt.executeUpdate("CREATE TABLE testBug4510 ("
1524                    + "field1 INT NOT NULL PRIMARY KEY AUTO_INCREMENT,"
1525                    + "field2 VARCHAR(100))");
1526            this.stmt
1527                    .executeUpdate("INSERT INTO testBug4510 (field1, field2) VALUES (32767, 'bar')");
1528
1529            PreparedStatement JavaDoc p = this.conn.prepareStatement(
1530                    "insert into testBug4510 (field2) values (?)",
1531                    Statement.RETURN_GENERATED_KEYS);
1532
1533            p.setString(1, "blah");
1534
1535            p.executeUpdate();
1536
1537            ResultSet JavaDoc rs = p.getGeneratedKeys();
1538            rs.next();
1539            System.out.println("Id: " + rs.getInt(1));
1540            rs.close();
1541        } finally {
1542            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4510");
1543        }
1544    }
1545
1546    /**
1547     * Tests fix for BUG#5012 -- ServerPreparedStatements dealing with return of
1548     * DECIMAL type don't work.
1549     *
1550     * @throws Exception
1551     * if the test fails.
1552     */

1553    public void testBug5012() throws Exception JavaDoc {
1554        PreparedStatement JavaDoc pStmt = null;
1555        String JavaDoc valueAsString = "12345.12";
1556
1557        try {
1558            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5012");
1559            this.stmt
1560                    .executeUpdate("CREATE TABLE testBug5012(field1 DECIMAL(10,2))");
1561            this.stmt.executeUpdate("INSERT INTO testBug5012 VALUES ("
1562                    + valueAsString + ")");
1563
1564            pStmt = this.conn
1565                    .prepareStatement("SELECT field1 FROM testBug5012");
1566            this.rs = pStmt.executeQuery();
1567            assertTrue(this.rs.next());
1568            assertEquals(new BigDecimal JavaDoc(valueAsString), this.rs
1569                    .getBigDecimal(1));
1570        } finally {
1571            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5012");
1572
1573            if (pStmt != null) {
1574                pStmt.close();
1575            }
1576        }
1577    }
1578
1579    /**
1580     * Tests for BUG#5191 -- PreparedStatement.executeQuery() gives
1581     * OutOfMemoryError
1582     *
1583     * @throws Exception
1584     * if the test fails.
1585     */

1586    public void testBug5191() throws Exception JavaDoc {
1587        PreparedStatement JavaDoc pStmt = null;
1588
1589        try {
1590            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5191Q");
1591            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5191C");
1592
1593            this.stmt.executeUpdate("CREATE TABLE testBug5191Q"
1594                    + "(QuestionId int NOT NULL AUTO_INCREMENT, "
1595                    + "Text VARCHAR(200), " + "PRIMARY KEY(QuestionId))");
1596
1597            this.stmt.executeUpdate("CREATE TABLE testBug5191C"
1598                    + "(CategoryId int, " + "QuestionId int)");
1599
1600            String JavaDoc[] questions = new String JavaDoc[] { "What is your name?",
1601                    "What is your quest?",
1602                    "What is the airspeed velocity of an unladen swollow?",
1603                    "How many roads must a man walk?", "Where's the tea?", };
1604
1605            for (int i = 0; i < questions.length; i++) {
1606                this.stmt.executeUpdate("INSERT INTO testBug5191Q(Text)"
1607                        + " VALUES (\"" + questions[i] + "\")");
1608                int catagory = (i < 3) ? 0 : i;
1609
1610                this.stmt.executeUpdate("INSERT INTO testBug5191C"
1611                        + "(CategoryId, QuestionId) VALUES (" + catagory + ", "
1612                        + i + ")");
1613                /*
1614                 * this.stmt.executeUpdate("INSERT INTO testBug5191C" +
1615                 * "(CategoryId, QuestionId) VALUES (" + catagory + ", (SELECT
1616                 * testBug5191Q.QuestionId" + " FROM testBug5191Q " + "WHERE
1617                 * testBug5191Q.Text LIKE '" + questions[i] + "'))");
1618                 */

1619            }
1620
1621            pStmt = this.conn.prepareStatement("SELECT qc.QuestionId, q.Text "
1622                    + "FROM testBug5191Q q, testBug5191C qc "
1623                    + "WHERE qc.CategoryId = ? "
1624                    + " AND q.QuestionId = qc.QuestionId");
1625
1626            int catId = 0;
1627            for (int i = 0; i < 100; i++) {
1628                execQueryBug5191(pStmt, catId);
1629            }
1630
1631        } finally {
1632            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5191Q");
1633            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5191C");
1634
1635            if (pStmt != null) {
1636                pStmt.close();
1637            }
1638        }
1639    }
1640
1641    public void testBug5235() throws Exception JavaDoc {
1642        Properties JavaDoc props = new Properties JavaDoc();
1643        props.setProperty("zeroDateTimeBehavior", "convertToNull");
1644
1645        Connection JavaDoc convertToNullConn = getConnectionWithProps(props);
1646        Statement JavaDoc convertToNullStmt = convertToNullConn.createStatement();
1647        try {
1648            convertToNullStmt.executeUpdate("DROP TABLE IF EXISTS testBug5235");
1649            convertToNullStmt
1650                    .executeUpdate("CREATE TABLE testBug5235(field1 DATE)");
1651            convertToNullStmt
1652                    .executeUpdate("INSERT INTO testBug5235 (field1) VALUES ('0000-00-00')");
1653
1654            PreparedStatement JavaDoc ps = convertToNullConn
1655                    .prepareStatement("SELECT field1 FROM testBug5235");
1656            this.rs = ps.executeQuery();
1657
1658            if (this.rs.next()) {
1659                Date JavaDoc d = (Date JavaDoc) rs.getObject("field1");
1660                System.out.println("date: " + d);
1661            }
1662        } finally {
1663            convertToNullStmt.executeUpdate("DROP TABLE IF EXISTS testBug5235");
1664        }
1665    }
1666
1667    public void testBug5510() throws Exception JavaDoc {
1668        // This is a server bug that should be fixed by 4.1.6
1669
if (versionMeetsMinimum(4, 1, 6)) {
1670            try {
1671                this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5510");
1672
1673                this.stmt
1674                        .executeUpdate("CREATE TABLE `testBug5510` ("
1675                                + "`a` bigint(20) NOT NULL auto_increment,"
1676                                + "`b` varchar(64) default NULL,"
1677                                + "`c` varchar(64) default NULL,"
1678                                + "`d` varchar(255) default NULL,"
1679                                + "`e` int(11) default NULL,"
1680                                + "`f` varchar(32) default NULL,"
1681                                + "`g` varchar(32) default NULL,"
1682                                + "`h` varchar(80) default NULL,"
1683                                + "`i` varchar(255) default NULL,"
1684                                + "`j` varchar(255) default NULL,"
1685                                + "`k` varchar(255) default NULL,"
1686                                + "`l` varchar(32) default NULL,"
1687                                + "`m` varchar(32) default NULL,"
1688                                + "`n` timestamp NOT NULL default CURRENT_TIMESTAMP on update"
1689                                + " CURRENT_TIMESTAMP,"
1690                                + "`o` int(11) default NULL,"
1691                                + "`p` int(11) default NULL,"
1692                                + "PRIMARY KEY (`a`)"
1693                                + ") ENGINE=InnoDB DEFAULT CHARSET=latin1");
1694                PreparedStatement JavaDoc pStmt = this.conn
1695                        .prepareStatement("INSERT INTO testBug5510 (a) VALUES (?)");
1696                pStmt.setNull(1, 0);
1697                pStmt.executeUpdate();
1698
1699            } finally {
1700                this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5510");
1701            }
1702        }
1703    }
1704
1705    /**
1706     * @param pStmt
1707     * @param catId
1708     * @throws SQLException
1709     */

1710    private void execQueryBug5191(PreparedStatement JavaDoc pStmt, int catId)
1711            throws SQLException JavaDoc {
1712        pStmt.setInt(1, catId);
1713
1714        this.rs = pStmt.executeQuery();
1715
1716        assertTrue(this.rs.next());
1717        assertTrue(this.rs.next());
1718        // assertTrue(rs.next());
1719

1720        assertFalse(this.rs.next());
1721    }
1722
1723    public void testBug5450() throws Exception JavaDoc {
1724        if (versionMeetsMinimum(4, 1)) {
1725            String JavaDoc table = "testBug5450";
1726            String JavaDoc column = "policyname";
1727
1728            try {
1729                Properties JavaDoc props = new Properties JavaDoc();
1730                props.setProperty("characterEncoding", "utf8");
1731
1732                Connection JavaDoc utf8Conn = getConnectionWithProps(props);
1733                Statement JavaDoc utfStmt = utf8Conn.createStatement();
1734
1735                this.stmt.executeUpdate("DROP TABLE IF EXISTS " + table);
1736
1737                this.stmt.executeUpdate("CREATE TABLE " + table
1738                        + "(policyid int NOT NULL AUTO_INCREMENT, " + column
1739                        + " VARCHAR(200), "
1740                        + "PRIMARY KEY(policyid)) DEFAULT CHARACTER SET utf8");
1741
1742                String JavaDoc pname0 = "inserted \uac00 - foo - \u4e00";
1743
1744                utfStmt.executeUpdate("INSERT INTO " + table + "(" + column
1745                        + ")" + " VALUES (\"" + pname0 + "\")");
1746
1747                this.rs = utfStmt.executeQuery("SELECT " + column + " FROM "
1748                        + table);
1749
1750                this.rs.first();
1751                String JavaDoc pname1 = this.rs.getString(column);
1752
1753                assertEquals(pname0, pname1);
1754                byte[] bytes = this.rs.getBytes(column);
1755
1756                String JavaDoc pname2 = new String JavaDoc(bytes, "utf-8");
1757                assertEquals(pname1, pname2);
1758
1759                utfStmt.executeUpdate("delete from " + table + " where "
1760                        + column + " like 'insert%'");
1761
1762                PreparedStatement JavaDoc s1 = utf8Conn.prepareStatement("insert into "
1763                        + table + "(" + column + ") values (?)");
1764
1765                s1.setString(1, pname0);
1766                s1.executeUpdate();
1767
1768                String JavaDoc byteesque = "byte " + pname0;
1769                byte[] newbytes = byteesque.getBytes("utf-8");
1770
1771                s1.setBytes(1, newbytes);
1772                s1.executeUpdate();
1773
1774                this.rs = utfStmt.executeQuery("select " + column + " from "
1775                        + table + " where " + column + " like 'insert%'");
1776                this.rs.first();
1777                String JavaDoc pname3 = this.rs.getString(column);
1778                assertEquals(pname0, pname3);
1779
1780                this.rs = utfStmt.executeQuery("select " + column + " from "
1781                        + table + " where " + column + " like 'byte insert%'");
1782                this.rs.first();
1783
1784                String JavaDoc pname4 = this.rs.getString(column);
1785                assertEquals(byteesque, pname4);
1786
1787            } finally {
1788                this.stmt.executeUpdate("DROP TABLE IF EXISTS " + table);
1789            }
1790        }
1791    }
1792
1793    public void testPStmtTypesBug() throws Exception JavaDoc {
1794        try {
1795            this.stmt.executeUpdate("DROP TABLE IF EXISTS testPStmtTypesBug");
1796            this.stmt
1797                    .executeUpdate("CREATE TABLE testPStmtTypesBug(field1 INT)");
1798            this.pstmt = this.conn
1799                    .prepareStatement("INSERT INTO testPStmtTypesBug VALUES (?)");
1800            this.pstmt.setObject(1, null, Types.INTEGER);
1801            this.pstmt.addBatch();
1802            this.pstmt.setInt(1, 1);
1803            this.pstmt.addBatch();
1804            this.pstmt.executeBatch();
1805
1806        } finally {
1807            this.stmt.executeUpdate("DROP TABLE IF EXISTS testPStmtTypesBug");
1808        }
1809    }
1810
1811    public void testTruncationWithChar() throws Exception JavaDoc {
1812        try {
1813            this.stmt
1814                    .executeUpdate("DROP TABLE IF EXISTS testTruncationWithChar");
1815            this.stmt
1816                    .executeUpdate("CREATE TABLE testTruncationWithChar (field1 char(2))");
1817
1818            this.pstmt = this.conn
1819                    .prepareStatement("INSERT INTO testTruncationWithChar VALUES (?)");
1820            this.pstmt.setString(1, "00");
1821            this.pstmt.executeUpdate();
1822        } finally {
1823            this.stmt
1824                    .executeUpdate("DROP TABLE IF EXISTS testTruncationWithChar");
1825        }
1826    }
1827
1828    /**
1829     * Tests fix for BUG#5133 -- PreparedStatement.toString() doesn't return
1830     * correct value if no parameters are present in statement.
1831     *
1832     * @throws Exception
1833     */

1834    public void testBug5133() throws Exception JavaDoc {
1835        String JavaDoc query = "SELECT 1";
1836        String JavaDoc output = this.conn.prepareStatement(query).toString();
1837        System.out.println(output);
1838
1839        assertTrue(output.indexOf(query) != -1);
1840    }
1841
1842    /**
1843     * Tests fix for BUG#5874, timezone correction goes in wrong 'direction'
1844     * when useTimezone=true and server timezone differs from client timezone.
1845     *
1846     * @throws Exception
1847     * if the test fails.
1848     */

1849    public void testBug5874() throws Exception JavaDoc {
1850        try {
1851            String JavaDoc clientTimezoneName = "America/Los_Angeles";
1852            String JavaDoc serverTimezoneName = "America/Chicago";
1853
1854            TimeZone.setDefault(TimeZone.getTimeZone(clientTimezoneName));
1855
1856            long epsillon = 3000; // 3 seconds difference
1857

1858            long clientTimezoneOffsetMillis = TimeZone.getDefault()
1859                    .getRawOffset();
1860            long serverTimezoneOffsetMillis = TimeZone.getTimeZone(
1861                    serverTimezoneName).getRawOffset();
1862
1863            long offsetDifference = clientTimezoneOffsetMillis
1864                    - serverTimezoneOffsetMillis;
1865
1866            Properties JavaDoc props = new Properties JavaDoc();
1867            props.put("useTimezone", "true");
1868            props.put("serverTimezone", serverTimezoneName);
1869
1870            Connection JavaDoc tzConn = getConnectionWithProps(props);
1871            Statement JavaDoc tzStmt = tzConn.createStatement();
1872            tzStmt.executeUpdate("DROP TABLE IF EXISTS timeTest");
1873            tzStmt
1874                    .executeUpdate("CREATE TABLE timeTest (tstamp DATETIME, t TIME)");
1875
1876            PreparedStatement JavaDoc pstmt = tzConn
1877                    .prepareStatement("INSERT INTO timeTest VALUES (?, ?)");
1878
1879            long now = System.currentTimeMillis(); // Time in milliseconds
1880
// since 1/1/1970 GMT
1881

1882            Timestamp JavaDoc nowTstamp = new Timestamp JavaDoc(now);
1883            Time JavaDoc nowTime = new Time JavaDoc(now);
1884
1885            pstmt.setTimestamp(1, nowTstamp);
1886            pstmt.setTime(2, nowTime);
1887            pstmt.executeUpdate();
1888
1889            rs = tzStmt.executeQuery("SELECT * from timeTest");
1890
1891            // Timestamps look like this: 2004-11-29 13:43:21
1892
SimpleDateFormat JavaDoc timestampFormat = new SimpleDateFormat JavaDoc(
1893                    "yyyy-MM-dd HH:mm:ss");
1894            SimpleDateFormat JavaDoc timeFormat = new SimpleDateFormat JavaDoc("HH:mm:ss");
1895
1896            while (rs.next()) {
1897                // Driver now converts/checks DATE/TIME/TIMESTAMP/DATETIME types
1898
// when calling getString()...
1899
String JavaDoc retrTimestampString = new String JavaDoc(rs.getBytes(1));
1900                Timestamp JavaDoc retrTimestamp = rs.getTimestamp(1);
1901
1902                java.util.Date JavaDoc timestampOnServer = timestampFormat
1903                        .parse(retrTimestampString);
1904
1905                long retrievedOffsetForTimestamp = retrTimestamp.getTime()
1906                        - timestampOnServer.getTime();
1907
1908                assertTrue(
1909                        "Difference between original timestamp and timestamp retrieved using client timezone is not "
1910                                + offsetDifference, (Math
1911                                .abs(retrievedOffsetForTimestamp
1912                                        - offsetDifference) < epsillon));
1913
1914                String JavaDoc retrTimeString = new String JavaDoc(rs.getBytes(2));
1915                Time JavaDoc retrTime = rs.getTime(2);
1916
1917                java.util.Date JavaDoc timeOnServerAsDate = timeFormat
1918                        .parse(retrTimeString);
1919                Time JavaDoc timeOnServer = new Time JavaDoc(timeOnServerAsDate.getTime());
1920
1921                long retrievedOffsetForTime = retrTime.getTime()
1922                        - timeOnServer.getTime();
1923
1924                assertTrue(
1925                        "Difference between original times and time retrieved using client timezone is not "
1926                                + offsetDifference,
1927                        (Math.abs(retrievedOffsetForTime - offsetDifference) < epsillon));
1928            }
1929        } finally {
1930            stmt.executeUpdate("DROP TABLE IF EXISTS timeTest");
1931        }
1932    }
1933
1934    public void testBug6823() throws SQLException JavaDoc {
1935        innerBug6823(true);
1936        innerBug6823(false);
1937    }
1938
1939    /**
1940     * @param continueBatchOnError
1941     * @throws SQLException
1942     */

1943    private void innerBug6823(boolean continueBatchOnError) throws SQLException JavaDoc {
1944        Properties JavaDoc continueBatchOnErrorProps = new Properties JavaDoc();
1945        continueBatchOnErrorProps.setProperty("continueBatchOnError", Boolean
1946                .toString(continueBatchOnError));
1947        this.conn = getConnectionWithProps(continueBatchOnErrorProps);
1948        Statement JavaDoc statement = conn.createStatement();
1949
1950        String JavaDoc tableName = "testBug6823";
1951
1952        createTable(tableName, "(id int not null primary key auto_increment,"
1953                + " strdata1 varchar(255) not null, strdata2 varchar(255),"
1954                + " UNIQUE INDEX (strdata1))");
1955
1956        PreparedStatement JavaDoc pStmt = this.conn.prepareStatement("INSERT INTO "
1957                + tableName + " (strdata1, strdata2) VALUES (?,?)");
1958
1959        int c = 0;
1960        addBatchItems(statement, pStmt, tableName, ++c);
1961        addBatchItems(statement, pStmt, tableName, ++c);
1962        addBatchItems(statement, pStmt, tableName, ++c);
1963        addBatchItems(statement, pStmt, tableName, c); // duplicate entry
1964
addBatchItems(statement, pStmt, tableName, ++c);
1965        addBatchItems(statement, pStmt, tableName, ++c);
1966
1967        int expectedUpdateCounts = continueBatchOnError ? 6 : 3;
1968
1969        BatchUpdateException JavaDoc e1 = null;
1970        BatchUpdateException JavaDoc e2 = null;
1971
1972        int[] updateCountsPstmt = null;
1973        try {
1974            updateCountsPstmt = pStmt.executeBatch();
1975        } catch (BatchUpdateException JavaDoc e) {
1976            e1 = e;
1977            updateCountsPstmt = e1.getUpdateCounts();
1978        }
1979
1980        int[] updateCountsStmt = null;
1981        try {
1982            updateCountsStmt = statement.executeBatch();
1983        } catch (BatchUpdateException JavaDoc e) {
1984            e2 = e;
1985            updateCountsStmt = e1.getUpdateCounts();
1986        }
1987
1988        assertNotNull(e1);
1989        assertNotNull(e2);
1990
1991        assertEquals(expectedUpdateCounts, updateCountsPstmt.length);
1992        assertEquals(expectedUpdateCounts, updateCountsStmt.length);
1993
1994        if (continueBatchOnError) {
1995            assertTrue(updateCountsPstmt[3] == Statement.EXECUTE_FAILED);
1996            assertTrue(updateCountsStmt[3] == Statement.EXECUTE_FAILED);
1997        }
1998
1999        int psRows = 0;
2000        this.rs = this.stmt.executeQuery("SELECT * from " + tableName
2001                + " WHERE strdata1 like \"ps_%\"");
2002        while (rs.next()) {
2003            psRows++;
2004        }
2005        assertTrue(psRows > 0);
2006
2007        int sRows = 0;
2008        this.rs = this.stmt.executeQuery("SELECT * from " + tableName
2009                + " WHERE strdata1 like \"s_%\"");
2010        while (rs.next()) {
2011            sRows++;
2012        }
2013        assertTrue(sRows > 0);
2014
2015        assertTrue(psRows + "!=" + sRows, psRows == sRows);
2016    }
2017
2018    private void addBatchItems(Statement JavaDoc statement, PreparedStatement JavaDoc pStmt,
2019            String JavaDoc tableName, int i) throws SQLException JavaDoc {
2020        pStmt.setString(1, "ps_batch_" + i);
2021        pStmt.setString(2, "ps_batch_" + i);
2022        pStmt.addBatch();
2023
2024        statement.addBatch("INSERT INTO " + tableName
2025                + " (strdata1, strdata2) VALUES " + "(\"s_batch_" + i
2026                + "\",\"s_batch_" + i + "\")");
2027    }
2028
2029    public void testBug7461() throws Exception JavaDoc {
2030        String JavaDoc tableName = "testBug7461";
2031
2032        try {
2033            createTable(tableName, "(field1 varchar(4))");
2034            File JavaDoc tempFile = File.createTempFile("mysql-test", ".txt");
2035            tempFile.deleteOnExit();
2036
2037            FileOutputStream JavaDoc fOut = new FileOutputStream JavaDoc(tempFile);
2038            fOut.write("abcdefghijklmnop".getBytes());
2039            fOut.close();
2040
2041            try {
2042                this.stmt.executeQuery("LOAD DATA LOCAL INFILE '"
2043                        + tempFile.toString() + "' INTO TABLE " + tableName);
2044            } catch (SQLException JavaDoc sqlEx) {
2045                this.stmt.getWarnings();
2046            }
2047
2048        } finally {
2049            dropTable(tableName);
2050        }
2051
2052    }
2053
2054    public void testServerPrepStmtDeadlock() throws Exception JavaDoc {
2055
2056        Connection JavaDoc c = getConnectionWithProps(null);
2057
2058        Thread JavaDoc testThread1 = new PrepareThread(c);
2059        Thread JavaDoc testThread2 = new PrepareThread(c);
2060        testThread1.start();
2061        testThread2.start();
2062        Thread.sleep(30000);
2063        assertTrue(testServerPrepStmtDeadlockCounter >= 10);
2064    }
2065
2066    public void testBug8181() throws Exception JavaDoc {
2067
2068        try {
2069            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug8181");
2070            this.stmt
2071                    .executeUpdate("CREATE TABLE testBug8181(col1 VARCHAR(20),col2 INT)");
2072
2073            this.pstmt = this.conn
2074                    .prepareStatement("INSERT INTO testBug8181(col1,col2) VALUES(?,?)");
2075
2076            for (int i = 0; i < 20; i++) {
2077                this.pstmt.setString(1, "Test " + i);
2078                this.pstmt.setInt(2, i);
2079                this.pstmt.addBatch();
2080            }
2081
2082            pstmt.executeBatch();
2083
2084        } finally {
2085            this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug8181");
2086
2087            if (this.pstmt != null) {
2088                this.pstmt.close();
2089            }
2090        }
2091    }
2092
2093    /**
2094     * Tests fix for BUG#8487 - PreparedStatements not creating streaming result
2095     * sets.
2096     *
2097     * @throws Exception
2098     * if the test fails.
2099     */

2100    public void testBug8487() throws Exception JavaDoc {
2101        try {
2102            this.pstmt = this.conn.prepareStatement("SELECT 1",
2103                    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
2104
2105            this.pstmt.setFetchSize(Integer.MIN_VALUE);
2106            this.rs = this.pstmt.executeQuery();
2107            try {
2108                this.conn.createStatement().executeQuery("SELECT 2");
2109                fail("Should have caught a streaming exception here");
2110            } catch (SQLException JavaDoc sqlEx) {
2111                assertTrue(sqlEx.getMessage() != null
2112                        && sqlEx.getMessage().indexOf("Streaming") != -1);
2113            }
2114
2115        } finally {
2116            if (this.rs != null) {
2117                while (this.rs.next())
2118                    ;
2119
2120                rs.close();
2121            }
2122
2123            if (this.pstmt != null) {
2124                this.pstmt.close();
2125            }
2126        }
2127    }
2128
2129    /*
2130     * public void testBug9595() throws Exception { double[] vals = new double[]
2131     * {52.21, 52.22, 52.23, 52.24};
2132     *
2133     * createTable("testBug9595", "(field1 DECIMAL(10,2), sortField INT)");
2134     *
2135     * this.pstmt = this.conn.prepareStatement("INSERT INTO testBug9595 VALUES
2136     * (?, ?)");
2137     * // Try setting as doubles for (int i = 0; i < vals.length; i++) {
2138     * this.pstmt.setDouble(1, vals[i]); this.pstmt.setInt(2, i);
2139     * this.pstmt.executeUpdate(); }
2140     *
2141     * this.pstmt = this.conn.prepareStatement("SELECT field1 FROM testBug9595
2142     * ORDER BY sortField"); this.rs = this.pstmt.executeQuery();
2143     *
2144     * int i = 0;
2145     *
2146     * while (this.rs.next()) { double valToTest = vals[i++];
2147     *
2148     * assertEquals(this.rs.getDouble(1), valToTest, 0.001);
2149     * assertEquals(this.rs.getBigDecimal(1).doubleValue(), valToTest, 0.001); }
2150     *
2151     * this.pstmt = this.conn.prepareStatement("INSERT INTO testBug9595 VALUES
2152     * (?, ?)");
2153     *
2154     * this.stmt.executeUpdate("TRUNCATE TABLE testBug9595");
2155     * // Now, as BigDecimals for (i = 0; i < vals.length; i++) { BigDecimal
2156     * foo = new BigDecimal(vals[i]);
2157     *
2158     * this.pstmt.setObject(1, foo, Types.DECIMAL, 2); this.pstmt.setInt(2, i);
2159     * this.pstmt.executeUpdate(); }
2160     *
2161     * this.pstmt = this.conn.prepareStatement("SELECT field1 FROM testBug9595
2162     * ORDER BY sortField"); this.rs = this.pstmt.executeQuery();
2163     *
2164     * i = 0;
2165     *
2166     * while (this.rs.next()) { double valToTest = vals[i++];
2167     * System.out.println(this.rs.getString(1));
2168     * assertEquals(this.rs.getDouble(1), valToTest, 0.001);
2169     * assertEquals(this.rs.getBigDecimal(1).doubleValue(), valToTest, 0.001); } }
2170     */

2171
2172    /**
2173     * Server doesn't accept everything as a server-side prepared statement, so
2174     * by default we scan for stuff it can't handle.
2175     *
2176     * @throws SQLException
2177     */

2178    public void testBug4718() throws SQLException JavaDoc {
2179        if (versionMeetsMinimum(4, 1, 0)) {
2180            this.pstmt = this.conn.prepareStatement("SELECT 1 LIMIT ?");
2181            assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
2182
2183            this.pstmt = this.conn.prepareStatement("SELECT 1 LIMIT 1");
2184            assertTrue(this.pstmt instanceof com.mysql.jdbc.ServerPreparedStatement);
2185
2186            this.pstmt = this.conn.prepareStatement("SELECT 1 LIMIT 1, ?");
2187            assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
2188
2189            try {
2190                this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4718");
2191                this.stmt
2192                        .executeUpdate("CREATE TABLE testBug4718 (field1 char(32))");
2193
2194                this.pstmt = this.conn
2195                        .prepareStatement("ALTER TABLE testBug4718 ADD INDEX (field1)");
2196                assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
2197
2198                this.pstmt = this.conn.prepareStatement("SELECT 1");
2199                assertTrue(this.pstmt instanceof ServerPreparedStatement);
2200
2201                this.pstmt = this.conn
2202                        .prepareStatement("UPDATE testBug4718 SET field1=1");
2203                assertTrue(this.pstmt instanceof ServerPreparedStatement);
2204
2205                this.pstmt = this.conn
2206                        .prepareStatement("UPDATE testBug4718 SET field1=1 LIMIT 1");
2207                assertTrue(this.pstmt instanceof ServerPreparedStatement);
2208
2209                this.pstmt = this.conn
2210                        .prepareStatement("UPDATE testBug4718 SET field1=1 LIMIT ?");
2211                assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
2212
2213                this.pstmt = this.conn
2214                        .prepareStatement("UPDATE testBug4718 SET field1='Will we ignore LIMIT ?,?'");
2215                assertTrue(this.pstmt instanceof ServerPreparedStatement);
2216
2217            } finally {
2218                this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4718");
2219            }
2220        }
2221    }
2222
2223    /**
2224     * Tests multiple statement support with fix for BUG#9704.
2225     *
2226     * @throws Exception
2227     * DOCUMENT ME!
2228     */

2229    public void testBug9704() throws Exception JavaDoc {
2230        if (versionMeetsMinimum(4, 1)) {
2231            Connection JavaDoc multiStmtConn = null;
2232            Statement JavaDoc multiStmt = null;
2233
2234            try {
2235                Properties JavaDoc props = new Properties JavaDoc();
2236                props.setProperty("allowMultiQueries", "true");
2237
2238                multiStmtConn = getConnectionWithProps(props);
2239
2240                multiStmt = multiStmtConn.createStatement();
2241
2242                multiStmt
2243                        .executeUpdate("DROP TABLE IF EXISTS testMultiStatements");
2244                multiStmt
2245                        .executeUpdate("CREATE TABLE testMultiStatements (field1 VARCHAR(255), field2 INT, field3 DOUBLE)");
2246                multiStmt
2247                        .executeUpdate("INSERT INTO testMultiStatements VALUES ('abcd', 1, 2)");
2248
2249                multiStmt
2250                        .execute("SELECT field1 FROM testMultiStatements WHERE field1='abcd';"
2251                                + "UPDATE testMultiStatements SET field3=3;"
2252                                + "SELECT field3 FROM testMultiStatements WHERE field3=3");
2253
2254                this.rs = multiStmt.getResultSet();
2255
2256                assertTrue(this.rs.next());
2257
2258                assertTrue("abcd".equals(this.rs.getString(1)));
2259                this.rs.close();
2260
2261                // Next should be an update count...
2262
assertTrue(!multiStmt.getMoreResults());
2263
2264                assertTrue("Update count was " + multiStmt.getUpdateCount()
2265                        + ", expected 1", multiStmt.getUpdateCount() == 1);
2266
2267                assertTrue(multiStmt.getMoreResults());
2268
2269                this.rs = multiStmt.getResultSet();
2270
2271                assertTrue(this.rs.next());
2272
2273                assertTrue(this.rs.getDouble(1) == 3);
2274
2275                // End of multi results
2276
assertTrue(!multiStmt.getMoreResults());
2277                assertTrue(multiStmt.getUpdateCount() == -1);
2278            } finally {
2279                if (multiStmt != null) {
2280                    multiStmt
2281                            .executeUpdate("DROP TABLE IF EXISTS testMultiStatements");
2282
2283                    multiStmt.close();
2284                }
2285
2286                if (multiStmtConn != null) {
2287                    multiStmtConn.close();
2288                }
2289            }
2290        }
2291    }
2292
2293    /**
2294     * Tests fix for BUG#10155, double quotes not recognized when parsing
2295     * client-side prepared statements.
2296     *
2297     * @throws Exception
2298     * if the test fails.
2299     */

2300    public void testBug10155() throws Exception JavaDoc {
2301        this.conn.prepareStatement(
2302                "SELECT \"Test question mark? Test single quote'\"")
2303                .executeQuery().close();
2304    }
2305
2306    public void testCsc4194() throws Exception JavaDoc {
2307
2308        Connection JavaDoc sjisConn = null;
2309        Connection JavaDoc windows31JConn = null;
2310
2311        try {
2312            String JavaDoc tableNameText = "testCsc4194Text";
2313            String JavaDoc tableNameBlob = "testCsc4194Blob";
2314
2315            createTable(tableNameBlob, "(field1 BLOB)");
2316            String JavaDoc charset = "";
2317
2318            if (versionMeetsMinimum(5, 0, 3) ||
2319                versionMeetsMinimum(4, 1, 12)) {
2320                charset = " CHARACTER SET cp932";
2321            } else if (versionMeetsMinimum(4, 1, 0)) {
2322                charset = " CHARACTER SET sjis";
2323            }
2324
2325            createTable(tableNameText, "(field1 TEXT)" + charset);
2326
2327            Properties JavaDoc windows31JProps = new Properties JavaDoc();
2328            windows31JProps.setProperty("useUnicode", "true");
2329            windows31JProps.setProperty("characterEncoding", "Windows-31J");
2330
2331            windows31JConn = getConnectionWithProps(windows31JProps);
2332            testCsc4194InsertCheckBlob(windows31JConn, tableNameBlob);
2333
2334            if (versionMeetsMinimum(4, 1, 0)) {
2335                testCsc4194InsertCheckText(windows31JConn, tableNameText,
2336                        "Windows-31J");
2337            }
2338
2339            Properties JavaDoc sjisProps = new Properties JavaDoc();
2340            sjisProps.setProperty("useUnicode", "true");
2341            sjisProps.setProperty("characterEncoding", "sjis");
2342
2343            sjisConn = getConnectionWithProps(sjisProps);
2344            testCsc4194InsertCheckBlob(sjisConn, tableNameBlob);
2345
2346            if (versionMeetsMinimum(5, 0, 3)) {
2347                testCsc4194InsertCheckText(sjisConn, tableNameText,
2348                        "Windows-31J");
2349            }
2350
2351        } finally {
2352
2353            if (windows31JConn != null) {
2354                windows31JConn.close();
2355            }
2356
2357            if (sjisConn != null) {
2358                sjisConn.close();
2359            }
2360        }
2361    }
2362
2363    
2364    /**
2365     * Tests for BUG#9288, parameter index out of range if
2366     * LIKE, ESCAPE '\' present in query.
2367     *
2368     * @throws Exception if the test fails.
2369     */

2370    /*
2371    public void testBug9288() throws Exception {
2372        String tableName = "testBug9288";
2373        PreparedStatement pStmt = null;
2374        
2375        try {
2376            createTable(tableName, "(field1 VARCHAR(32), field2 INT)");
2377            pStmt = ((com.mysql.jdbc.Connection)this.conn).clientPrepareStatement(
2378                    "SELECT COUNT(1) FROM " +
2379                    tableName + " WHERE "
2380                    + "field1 LIKE '%' ESCAPE '\\' AND "
2381                    + "field2 > ?");
2382            pStmt.setInt(1, 0);
2383
2384            this.rs = pStmt.executeQuery();
2385        } finally {
2386            if (this.rs != null) {
2387                this.rs.close();
2388                this.rs = null;
2389            }
2390            
2391            if (pStmt != null) {
2392                pStmt.close();
2393            }
2394        }
2395    }
2396    */

2397    
2398    /*
2399    public void testBug10999() throws Exception {
2400        if (versionMeetsMinimum(5, 0, 5)) {
2401    
2402            String tableName = "testBug10999";
2403            String updateTrigName = "testBug10999Update";
2404            String insertTrigName = "testBug10999Insert";
2405            try {
2406                createTable(tableName,
2407                        "(pkfield INT PRIMARY KEY NOT NULL AUTO_INCREMENT, field1 VARCHAR(32))");
2408                
2409                try {
2410                    this.stmt.executeUpdate("DROP TRIGGER " + updateTrigName);
2411                } catch (SQLException sqlEx) {
2412                    // ignore for now
2413                }
2414                
2415                this.stmt.executeUpdate("CREATE TRIGGER " + updateTrigName
2416                        + " AFTER UPDATE ON "
2417                        + tableName +
2418                        " FOR EACH ROW "
2419                        + "BEGIN "
2420                        + "END");
2421    
2422                try {
2423                    this.stmt.executeUpdate("DROP TRIGGER " + insertTrigName);
2424                } catch (SQLException sqlEx) {
2425                    // ignore
2426                }
2427                
2428                this.stmt.executeUpdate("CREATE TRIGGER " + insertTrigName
2429                + " AFTER INSERT ON " + tableName
2430                + " FOR EACH ROW "
2431                + " BEGIN "
2432                + "END");
2433                
2434                this.conn.setAutoCommit(false);
2435                
2436                String updateSQL = "INSERT INTO " +
2437                    tableName + " (field1) VALUES ('abcdefg')";
2438                int rowCount = this.stmt.executeUpdate(updateSQL,
2439                        Statement.RETURN_GENERATED_KEYS);
2440
2441                this.rs = stmt.getGeneratedKeys();
2442                                if (rs.next()) {
2443                                    System.out.println(rs.getInt(1));
2444                                       int id = rs.getInt(1);
2445                                        //if (log.isDebugEnabled())
2446                                         // log.debug("Retrieved ID = " + id);
2447                                }
2448                                //else {
2449                                    //log.error("Can't retrieve ID with getGeneratedKeys.");
2450
2451                                    // Retrieve ID using a SELECT statement instead.
2452                                   // querySQL = "SELECT id from tab1 WHERE ...";
2453
2454                                    //if (log.isDebugEnabled())
2455                                     // log.debug(querySQL);
2456
2457                                    //rs = stmt.executeQuery(querySQL);
2458                this.rs = this.stmt.executeQuery("SELECT pkfield FROM " + tableName);
2459                
2460            } finally {
2461                this.conn.setAutoCommit(true);
2462
2463                try {
2464                    this.stmt.executeUpdate("DROP TRIGGER IF EXISTS " + insertTrigName);
2465                } catch (SQLException sqlEx) {
2466                    // ignore
2467                }
2468                
2469                try {
2470                    this.stmt.executeUpdate("DROP TRIGGER IF EXISTS " + updateTrigName);
2471                } catch (SQLException sqlEx) {
2472                    // ignore
2473                }
2474            }
2475        }
2476    }
2477    */

2478    
2479    /**
2480     * Tests fix for BUG#11115, Varbinary data corrupted when using server-side
2481     * prepared statements.
2482     */

2483    public void testBug11115() throws Exception JavaDoc {
2484        String JavaDoc tableName = "testBug11115";
2485        
2486        if (versionMeetsMinimum(4, 1, 0)) {
2487             
2488             createTable(tableName, "(pwd VARBINARY(30)) TYPE=InnoDB DEFAULT CHARACTER SET utf8");
2489             
2490             byte[] bytesToTest = new byte[] { 17, 120, -1, -73, -5 };
2491             
2492             PreparedStatement JavaDoc insStmt = this.conn.prepareStatement("INSERT INTO " + tableName + " (pwd) VALUES (?)");
2493             insStmt.setBytes(1, bytesToTest);
2494             insStmt.executeUpdate();
2495             
2496             this.rs = this.stmt.executeQuery("SELECT pwd FROM " + tableName);
2497             this.rs.next();
2498             
2499             byte[] fromDatabase = this.rs.getBytes(1);
2500
2501             assertEquals(bytesToTest.length, fromDatabase.length);
2502             
2503             for (int i = 0; i < bytesToTest.length; i++) {
2504                 assertEquals(bytesToTest[i], fromDatabase[i]);
2505             }
2506             
2507             this.rs = this.conn.prepareStatement("SELECT pwd FROM " + tableName).executeQuery();
2508             this.rs.next();
2509             
2510             fromDatabase = this.rs.getBytes(1);
2511             
2512             assertEquals(bytesToTest.length, fromDatabase.length);
2513             
2514             for (int i = 0; i < bytesToTest.length; i++) {
2515                 assertEquals(bytesToTest[i], fromDatabase[i]);
2516             }
2517        }
2518    }
2519    
2520    public void testNullClob() throws Exception JavaDoc {
2521        createTable("testNullClob", "(field1 TEXT NULL)");
2522        
2523        PreparedStatement JavaDoc pStmt = null;
2524        
2525        try {
2526            pStmt = this.conn.prepareStatement("INSERT INTO testNullClob VALUES (?)");
2527            pStmt.setClob(1, null);
2528            pStmt.executeUpdate();
2529        } finally {
2530            if (pStmt != null) {
2531                pStmt.close();
2532            }
2533        }
2534    }
2535    
2536    private void testCsc4194InsertCheckBlob(Connection JavaDoc c, String JavaDoc tableName)
2537            throws Exception JavaDoc {
2538        byte[] bArray = new byte[] { (byte) 0xac, (byte) 0xed, (byte) 0x00,
2539                (byte) 0x05 };
2540
2541        PreparedStatement JavaDoc testStmt = c.prepareStatement("INSERT INTO "
2542                + tableName + " VALUES (?)");
2543        testStmt.setBytes(1, bArray);
2544        testStmt.executeUpdate();
2545
2546        this.rs = c.createStatement().executeQuery(
2547                "SELECT field1 FROM " + tableName);
2548        assertTrue(this.rs.next());
2549        assertEquals(getByteArrayString(bArray), getByteArrayString(this.rs
2550                .getBytes(1)));
2551        this.rs.close();
2552    }
2553
2554    private void testCsc4194InsertCheckText(Connection JavaDoc c, String JavaDoc tableName,
2555            String JavaDoc encoding) throws Exception JavaDoc {
2556        byte[] kabuInShiftJIS = { (byte) 0x87, // a double-byte
2557
// charater("kabu") in Shift JIS
2558
(byte) 0x8a, };
2559
2560        String JavaDoc expected = new String JavaDoc(kabuInShiftJIS, encoding);
2561        PreparedStatement JavaDoc testStmt = c.prepareStatement("INSERT INTO "
2562                + tableName + " VALUES (?)");
2563        testStmt.setString(1, expected);
2564        testStmt.executeUpdate();
2565
2566        this.rs = c.createStatement().executeQuery(
2567                "SELECT field1 FROM " + tableName);
2568        assertTrue(this.rs.next());
2569        assertEquals(expected, this.rs.getString(1));
2570        this.rs.close();
2571    }
2572
2573    private String JavaDoc getByteArrayString(byte[] ba) {
2574        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
2575        if (ba != null) {
2576            for (int i = 0; i < ba.length; i++) {
2577                buffer.append("0x" + Integer.toHexString(ba[i] & 0xff) + " ");
2578            }
2579        } else {
2580            buffer.append("null");
2581        }
2582        return buffer.toString();
2583    }
2584
2585}
2586
Popular Tags