-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathTTJdbcExamples.java
1159 lines (948 loc) · 32.9 KB
/
TTJdbcExamples.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Universal Permissive License v 1.0 as shown
* at http://oss.oracle.com/licenses/upl
*
* TTJdbcExamples.java demonstrates how to connect, disconnect, and
* run some basic features of TimesTen, through the TimesTen JDBC
* Driver.
*
* Usage: TTJdbcExamples [-h] [-t] [-c] [-run num] [[-dsn] dsnname]
* -h[elp] Print this usage message and exit
* -t[race] Turn on JDBC driver debug tracing
* -c[lient] Connect using client/server (default is direct connect)
* -run num Example number to run (Default is run all)
* -dsn Name of the data store to connect to (optional)
*
* Example number values:
* 1 Loads appropriate driver for the connection type
* 2 Connects to and disconnect from specified data store
* 3 Shows operations performed by a typical application
* 4 Shows how to change and print a query plan
* 5 Shows how to use the batch update facility
*
* Example command lines:
* java TTJdbcExamples
* java TTJdbcExamples sampledb
* java TTJdbcExamples -run 2 sampledb
* java TTJdbcExamples -client -run 2 -dsn sampledbCS
*
*/
import java.io.*;
import java.text.*;
import java.sql.*;
import java.lang.ClassNotFoundException;
import java.lang.Integer;
/**
* <code>TTJdbcExamples</code> uses the TimesTen JDBC Driver to
* demonstrate how to connect, disconnect, and exercise various
* database functionalities within TimesTen.
*/
public class TTJdbcExamples
{
/**
* The name of the TimesTen JDBC Driver (direct connection)
*/
private static final String DIRECT_DRIVER = "com.timesten.jdbc.TimesTenDriver";
/**
* The connection prefix of the TimesTen JDBC Driver (direct connection)
*/
private static final String DIRECT_CONNECT_PREFIX = "jdbc:timesten:direct:";
/**
* The name of the TimesTen JDBC Driver (client connection)
*/
private static final String CLIENT_DRIVER = "com.timesten.jdbc.TimesTenClientDriver";
/**
* The connection prefix of the TimesTen JDBC Driver (client connection)
*/
private static final String CLIENT_CONNECT_PREFIX = "jdbc:timesten:client:";
// Static variables - used by main
/**
* Flag indicating whether a "signal" has been received.
* This flag is set by our shutdown hook thread.
*/
static boolean hasReceivedSignal = false;
/**
* Flag indicating whether the shutdown hook thread should wait
* and hold-up the JVM exit so that the running examples can
* implement a clean exit first.
* This flag is set only when the examples are being run.
*/
static boolean shouldWait = false;
/**
* A synchronization object used by the shutdown hook thread to
* wait for an orderly database disconnect before exiting.
*/
static Object stopMonitor;
// Instance attributes - used by instances of the TTJdbcExamples object.
/**
* Name of driver to load
*/
private String myDriver;
/**
* Connection url
*/
private String myUrl;
/**
* Connection Password
*/
// private String myPassword = null;
static public String myPassword = null;
/**
* Connection Username
*/
// private String myUsername = null;
static public String myUsername = null;
/**
* What example to run
*/
private int runWhat;
/**
* Flag is true if the driver has been loaded
*/
private boolean isDriverLoaded;
/**
* Flag to indicate if a database connection is live
*/
private boolean isConnected = false;
// Methods
//--------------------------------------------------
//
// Function: getConsoleString
//
// Description: Read a String from the console and return it
//
//--------------------------------------------------
static private String getConsoleString (String what) {
String temp = null;
try {
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader( isr );
temp = br.readLine();
} catch (IOException e)
{
System.out.println();
System.out.println("Problem reading the " + what);
System.out.println();
}
return temp;
}
//--------------------------------------------------
//
// Function: getUsername
//
// Description: Assign the username
//
//--------------------------------------------------
static private void getUsername() {
// Default username for APPUSER
// System.out.println();
// System.out.print("Username: ");
// TTJdbcExamples.myUsername = getConsoleString("Username");
TTJdbcExamples.myUsername = "appuser";
}
//--------------------------------------------------
//
// Function: getPassword
//
// Description: Assign the password
//
//--------------------------------------------------
static private void getPassword() {
System.out.println();
TTJdbcExamples.myPassword = PasswordField.readPassword("Enter password for 'appuser': ");
}
/**
* Check if a "signal" is pending - i.e. the shutdown hook
* thread has been entered.
*/
private static boolean IsSignalPending()
{
return (hasReceivedSignal == true);
}
/**
* Calls IsSignalPending() and throws an exception if true.
*/
private static boolean CheckIfStopIsRequested()
throws InterruptedException
{
if (IsSignalPending() == true) {
throw new InterruptedException("We are being requested to stop!");
}
return false;
}
/**
* Prints uage information to System.err stream
*/
public static void usage()
{
System.err.println(
"\nUsage: TTJdbcExamples [-h] [-t] [-c] [-run num] [[-dsn] dsnname]\n" +
" -h[elp]\tPrint this usage message and exit\n" +
" -t[race]\tTurn on JDBC driver debug tracing\n" +
" -c[lient]\tConnect using client/server (default is direct connect)\n" +
" -run num\tExample number to run (Default is run all)\n" +
" -dsn\tName of the database to connect to (optional)\n" +
"\n Example number values:\n" +
" 1 Loads appropriate driver for the connection type\n" +
" 2 Connects to and disconnect from specified data store\n" +
" 3 Shows operations performed by a typical application\n" +
" 4 Shows how to change and print a query plan\n" +
" 5 Shows how to use the batch update facility\n" +
"\n\tExample command lines:\n" +
" java TTJdbcExamples\n"+
" java TTJdbcExamples " + tt_version.sample_DSN + "\n"+
" java TTJdbcExamples -run 2 " + tt_version.sample_DSN + "\n" +
" java TTJdbcExamples -client -run 2 -dsn " +
tt_version.sample_DSN_CS );
}
/**
* Start of program.
*
* Parses the arguments.
* Instantiates the TTJdbcExamples object.
* Runs the examples.
*/
public static void main(String args[])
{
String dsnname = null;
boolean isCSConn = false;
boolean doTrace = false;
int whatToRun = 0;
int argInd = 0;
// Iterate over all of the arguments
for (argInd = 0; argInd < args.length; argInd++) {
// Break out if argument does not start with '-'
if (args[argInd].charAt(0) != '-') {
break;
}
if (args[argInd].equalsIgnoreCase("-h") ||
args[argInd].equalsIgnoreCase("-help")) {
usage();
System.exit(0);
} else if (args[argInd].equalsIgnoreCase("-c") ||
args[argInd].equalsIgnoreCase("-client")) {
isCSConn = true;
} else if (args[argInd].equalsIgnoreCase("-t") ||
args[argInd].equalsIgnoreCase("-trace")) {
doTrace = true;
} else if (args[argInd].equals("-r") ||
args[argInd].equals("-run")) {
argInd++;
if (argInd >= args.length) {
System.err.println("Error: -run option requires an argument");
usage();
System.exit(1);
}
try {
whatToRun = Integer.parseInt(args[argInd]);
} catch (NumberFormatException ex) {
System.err.println("Error: -run option requires a number.");
usage();
System.exit(1);
}
if (whatToRun < 0 || whatToRun > 6) {
System.err.println("Error: -run option requires a number between 1 and 6");
usage();
System.exit(1);
}
} else if (args[argInd].equalsIgnoreCase("-dsn")) {
argInd++;
if (argInd >= args.length) {
System.err.println("Error: -dsn option requires an argument");
usage();
System.exit(1);
}
dsnname = args[argInd];
} else {
System.err.println("Error: unknown argument " + args[argInd]);
usage();
System.exit(1);
}
}
// If there are any left over arguments, treat it as a dsnname;
if (argInd < args.length) {
if (dsnname != null) {
System.err.println("Error: extra argument. Parsing stopped at " + args[argInd]);
usage();
System.exit(1);
}
dsnname = args[argInd];
argInd++;
}
// If dsnname is not set at this point, then default it.
if (dsnname == null || dsnname.length() == 0) {
// Default the DSN
dsnname = tt_version.sample_DSN;
}
// If there are any left over arguments, it is an error at this point.
if (argInd < args.length) {
System.err.println("Error: too many arguments. Parsing stopped at " + args[argInd]);
usage();
System.exit(1);
}
// Enable tracing in TimesTen JDBC driver for debugging
if (doTrace) {
DriverManager.setLogWriter(new PrintWriter(System.out, true));
}
System.out.println();
System.out.println("Connecting to the database ...");
// Prompt for the Username and Password
getUsername();
getPassword();
// Construct the example-running object
TTJdbcExamples examples;
if (isCSConn) {
examples = new TTJdbcExamples(CLIENT_DRIVER,
CLIENT_CONNECT_PREFIX + dsnname,
whatToRun);
} else {
examples = new TTJdbcExamples(DIRECT_DRIVER,
DIRECT_CONNECT_PREFIX + dsnname,
whatToRun);
}
// Use shutdown hooks to cleanly exit the application in
// the event of a JVM shutdown notification
stopMonitor = new Object();
Runtime.getRuntime().addShutdownHook(new Thread("Shutdown thread") {
public void run()
{
synchronized (stopMonitor) {
if (shouldWait) {
// System.out.println("Shutdown thread Waiting");
hasReceivedSignal = true;
try {
// Wait for OK to proceed
stopMonitor.wait(); // Might want have time limit.
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println("Leaving Shutdown thread");
}
}
}
});
synchronized (stopMonitor) {
shouldWait = true;
}
// Run the examples
int exitCode = examples.runExamples();
synchronized (stopMonitor) {
shouldWait = false;
stopMonitor.notify();
}
System.exit(exitCode);
}
/**
* prints all attributes of a SQLException object to
* System.err and all chained exceptions.
*/
public static void reportSQLException(SQLException ex)
{
int errCount = 0;
while (ex != null) {
System.err.println ("\n\t----- SQL Error -----");
System.err.println ("\tError Message: " + ex.getMessage ());
if (errCount == 0) {
ex.printStackTrace ();
}
System.err.println ("\tSQL State: " + ex.getSQLState ());
System.err.println ("\tNative Error Code: " + ex.getErrorCode ());
System.err.println ("");
ex = ex.getNextException ();
errCount ++;
}
}
/**
* prints all attributes of a SQLWarning object to
* System.err and all chained warnings
*/
public static void reportSQLWarning(SQLWarning wn)
{
int warnCount = 0;
while (wn != null) {
System.err.println ("\n\t----- SQL Warning -----");
// Is this a regular SQLWarning object or a DataTruncation object?
if (wn instanceof DataTruncation) {
DataTruncation trn = (DataTruncation) wn;
System.err.println ("\tData Truncation Warning: " + trn.getMessage ());
if (warnCount == 0) {
trn.printStackTrace ();
}
System.err.println ("\tSQL State: " + trn.getSQLState ());
System.err.println ("\tNative Error Code: " + trn.getErrorCode ());
System.err.println ("\n\tgetIndex (): " + trn.getIndex ());
System.err.println ("\tgetParameter (): " + trn.getParameter ());
System.err.println ("\tgetRead (): " + trn.getRead ());
System.err.println ("\tgetDataSize (): " + trn.getDataSize ());
System.err.println ("\tgetTransferSize (): " + trn.getTransferSize ());
} else {
System.err.println ("\tWarning Message: " + wn.getMessage ());
if (warnCount == 0) {
wn.printStackTrace ();
}
System.err.println ("\tSQL State: " + wn.getSQLState ());
System.err.println ("\tNative Error Code: " + wn.getErrorCode ());
}
System.err.println ("");
wn = wn.getNextWarning ();
warnCount++;
}
}
/**
* Constructs a TTJdbcExamples object and initialize myDriver and myUrl
*/
public TTJdbcExamples(String driver, String url, int runWhat)
{
this.myDriver = driver;
System.out.println();
System.out.println("TTJdbcExamples.constructor: using DRIVER: " + myDriver);
this.myUrl = url;
System.out.println("TTJdbcExamples.constructor: using URL: " + myUrl);
System.out.println("TTJdbcExamples.constructor: using USER: " + myUsername);
System.out.println();
this.runWhat = runWhat;
this.isDriverLoaded = false;
}
/**
* Runs the examples
*/
public int runExamples()
{
int retCode = 0;
try {
switch(runWhat) {
case 1:
// If this method runs successfully that
// means system is able to find the driver
// classes and libraries
loadDriver();
break;
case 2:
// If this method runs successfully then TimesTen
// is running and the DSN is configured correctly.
connectAndDisconnect();
break;
case 3:
// Demonstrates basic database operations
elementaryOperations();
break;
case 4:
// Demonstrates how to change and print a query plan
changeQueryPlan();
break;
case 5:
// Demonstrates how to use the batch update facility
batchExecution();
break;
default:
// run all the examples by default
loadDriver();
if (IsSignalPending() == true) break;
connectAndDisconnect();
if (IsSignalPending() == true) break;
elementaryOperations();
if (IsSignalPending() == true) break;
changeQueryPlan();
if (IsSignalPending() == true) break;
batchExecution();
}
System.out.println("Done.");
} catch (ClassNotFoundException ex) {
retCode=2;
} catch (SQLException ex) {
retCode=3;
}
// Warning: if there is still a connection to the data store
// at this point, then the data store will be invalidated
// when this program exits.
if (isConnected == true) {
System.out.println("Warning: exiting without disconnecting from data store!");
}
return retCode;
}
/**
* Demonstrates how to load a TimesTen JDBC Driver
*/
public void loadDriver()
{
if (!isDriverLoaded) {
System.out.println("TTJdbcExamples.loadDriver()");
try {
// Load TimesTen JDBC driver using Class.forName()
Class.forName(this.myDriver);
isDriverLoaded = true;
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
/**
* Demonstrates how to connect to and disconnect from TimesTen
*/
public void connectAndDisconnect()
{
System.out.println("TTJdbcExamples.connectAndDisconnect()");
// Load TimesTen JDBC driver if necessary
loadDriver();
Connection con = null;
try {
// Open a connection
System.out.println("Open a connection.");
isConnected = true;
con = DriverManager.getConnection(myUrl, myUsername, myPassword);
// Report any SQLWarnings on the connection
reportSQLWarning(con.getWarnings());
CheckIfStopIsRequested();
// Fall through to con.close() in the finally clause
} catch (SQLException ex) {
reportSQLException(ex);
// Fall through to con.close() in the finally clause
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
// Fall through to con.close() in the finally clause
} finally {
try {
if (con != null && con.isClosed() == false) {
// Close the connection
System.out.println("Close the connection.");
con.close();
}
isConnected = false;
} catch (SQLException ex) {
reportSQLException(ex);
}
}
}
/**
* Demonstrates creating a table, creating an index, preparing
* and end executing an insert, and a selecting from the table.
*/
public void elementaryOperations()
{
int[] intValues = { 23125, 1125 };
String[] strValues = { "John Smith", "Sam Jones" };
System.out.println("TTJdbcExamples.elementaryOperations()");
// Load TimesTen JDBC driver if necessary
loadDriver();
Connection con = null;
try {
// Open a connection
System.out.println("Open a connection.");
isConnected = true;
con = DriverManager.getConnection(myUrl, myUsername, myPassword);
// Report any SQLWarnings from the last call
reportSQLWarning(con.getWarnings());
CheckIfStopIsRequested();
// Create a statement object
System.out.println("Create a statement object.");
Statement stmt = con.createStatement();
// Create a table
System.out.println("Creating table NameID.");
stmt.executeUpdate
("CREATE TABLE NameID(id INTEGER, name VARCHAR(50))");
// Report any SQLWarnings on the connection
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
// Create an index
System.out.println("Creating index IxID.");
stmt.executeUpdate("CREATE INDEX IxID ON NameID (id)");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
// Prepare a statement
System.out.println("Preparing an insert statement.");
PreparedStatement pstmt = con.prepareStatement
( "INSERT INTO NameID VALUES (?, ?)" );
// Insert data using prepared statements
System.out.println("Inserting data");
for(int i=0; i<2; i++) {
pstmt.setInt(1, intValues[i]);
pstmt.setString(2, strValues[i]);
pstmt.executeUpdate();
// Report any SQLWarnings from the last call
reportSQLWarning(pstmt.getWarnings());
CheckIfStopIsRequested();
}
// Close the prepared statement
System.out.println("Close the prepared statement.");
pstmt.close();
// Excute the select query
System.out.println("Executing query");
ResultSet rs = stmt.executeQuery("SELECT * FROM NameID");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
int numCols = rs.getMetaData().getColumnCount();
// Fetch data
System.out.println("Fetching data");
System.out.println("Data:");
while (rs.next()) {
// Report any SQLWarnings from the last call
reportSQLWarning(rs.getWarnings());
CheckIfStopIsRequested();
for (int i = 1; i <= numCols; i++) {
System.out.print("\t"+rs.getObject(i));
// Report any SQLWarnings from the last call
reportSQLWarning(rs.getWarnings());
CheckIfStopIsRequested();
}
System.out.println();
}
// Close the result set
System.out.println("Close the result set.");
rs.close();
// Delete data
System.out.println("Deleting data.");
stmt.executeUpdate
("DELETE FROM NameID WHERE name LIKE 'S%' ");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
// Drop index
System.out.println("Dropping index IxID.");
stmt.executeUpdate("DROP INDEX IxID ");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
//Drop table
System.out.println("Dropping table NameID.");
stmt.executeUpdate("DROP TABLE NameID");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
// Close the statement object
System.out.println("Close the statement.");
stmt.close();
// Fall through to con.close() in the finally clause
} catch (SQLException ex) {
reportSQLException(ex);
// Fall through to con.close() in the finally clause
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
// Fall through to con.close() in the finally clause
} finally {
try {
if (con != null && con.isClosed() == false) {
// Close the connection
System.out.println("Close the connection.");
con.close();
}
isConnected = false;
} catch (SQLException ex) {
reportSQLException(ex);
}
}
}
// ******************************************************************
// Method:
// optimizerExample
//
// Description:
// shows how to influence the query optimizer
//
// ******************************************************************
public void changeQueryPlan()
throws ClassNotFoundException, SQLException
{
boolean inXact = false;
Connection con = null;
Statement stmt = null;
PreparedStatement pStmt1 = null;
PreparedStatement pStmt2 = null;
CallableStatement cStmt = null;
ResultSet rs = null;
ResultSet rsPlan = null;
int numCols = 0;
System.out.println("\nChange and Print a Query Plan");
System.out.println( "-----------------------------");
// Load driver
loadDriver();
try {
// Connect to a TimesTen DSN
System.out.println("Open a connection.");
isConnected = true;
con = DriverManager.getConnection(myUrl, myUsername, myPassword);
// Report any SQLWarnings from the last call
reportSQLWarning(con.getWarnings());
CheckIfStopIsRequested();
con.setAutoCommit(false);
inXact = true;
// create tables
stmt = con.createStatement();
System.out.println("Create tables.");
stmt.executeUpdate("CREATE TABLE Tbl1(key INT)");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
stmt.executeUpdate("CREATE TABLE Tbl2(key INT)");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
// create indexes
System.out.println("Create indexes.");
stmt.executeUpdate("CREATE UNIQUE INDEX ixTbl1 ON Tbl1(key)");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
stmt.executeUpdate("CREATE UNIQUE INDEX ixTbl2 ON Tbl2(key)");
// Report any SQLWarnings from the last call
reportSQLWarning(stmt.getWarnings());
CheckIfStopIsRequested();
System.out.println("Prepare insert statements.");
pStmt1=con.prepareStatement("INSERT INTO Tbl1 VALUES (?)");
pStmt2=con.prepareStatement("INSERT INTO Tbl2 VALUES (?)");
// load data
System.out.println("Loading the data.");
for (int i=0; i<1000; i++) {
pStmt1.setInt(1, i);
pStmt1.executeUpdate();
// Report any SQLWarnings from the last call
reportSQLWarning(pStmt1.getWarnings());
CheckIfStopIsRequested();
pStmt2.setInt(1, i);
pStmt2.executeUpdate();
// Report any SQLWarnings from the last call
reportSQLWarning(pStmt2.getWarnings());
CheckIfStopIsRequested();
}
// prepare a call to disbale merge join
System.out.println("Turn off MergeJoin.");
cStmt = con.prepareCall("{CALL ttOptSetFlag('MergeJoin', 0)}");
cStmt.execute();
// Report any SQLWarnings from the last call
reportSQLWarning(cStmt.getWarnings());
CheckIfStopIsRequested();
// select from the table
System.out.println("Prepare select from plan.");
pStmt2=con.prepareStatement("SELECT * FROM sys.plan");
System.out.println("Turn on plan generator.");
cStmt = con.prepareCall("{ CALL ttOptSetFlag('GenPlan', 1)}");
cStmt.execute();
System.out.println("Prepare the join query.");
pStmt1=con.prepareStatement("SELECT * FROM Tbl1, Tbl2 "+
"WHERE Tbl1.key = Tbl2.key");
System.out.println("Execute plan query.");
rsPlan = pStmt2.executeQuery();
// Report any SQLWarnings from the last call
reportSQLWarning(pStmt2.getWarnings());
CheckIfStopIsRequested();
rs = pStmt1.executeQuery();
// Report any SQLWarnings from the last call
reportSQLWarning(pStmt1.getWarnings());
CheckIfStopIsRequested();
numCols=rsPlan.getMetaData().getColumnCount();
System.out.println("\nThe query optimizer plan " +
"for the join query:");
while(rsPlan.next()) {
// Report any SQLWarnings from the last call
reportSQLWarning(rsPlan.getWarnings());
CheckIfStopIsRequested();
for (int i = 1; i <= numCols; i++) {
System.out.print(rsPlan.getObject(i)+"\t");
// Report any SQLWarnings from the last call
reportSQLWarning(rsPlan.getWarnings());
CheckIfStopIsRequested();
}
System.out.println();
}
System.out.println();
// fetch the next row from the result set
int rowCt=0;
while(rs.next()) {
rowCt++;
CheckIfStopIsRequested();
}
System.out.println("Number of rows from select query = "+rowCt);
con.commit();
inXact = false;
System.out.println("Close objects.");
rsPlan.close();
rs.close();
pStmt1.close();
pStmt2.close();
cStmt.close();
CheckIfStopIsRequested();
inXact = true;
stmt.executeUpdate("DROP TABLE Tbl1");
stmt.executeUpdate("DROP TABLE Tbl2");
con.commit();
inXact = false;
stmt.close();
} catch (SQLException ex) {
reportSQLException(ex);
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
// Fall through to con.close() below
} finally {
try {
if (con != null && con.isClosed() == false) {
if (inXact) {
System.out.println ("\nRoll back uncommitted transaction.");
con.rollback();
inXact = false;
}
System.out.println("Close the connection.");
con.close();
}
isConnected = false;
} catch (SQLException ex) {
reportSQLException(ex);
}
}
}
// ******************************************************************
// Method:
// batchExecution
//
// Description:
// shows how to use the batch update facility
//
// ******************************************************************
public void batchExecution()
throws ClassNotFoundException, SQLException
{
boolean inXact = false;
Connection con = null;
Statement stmt = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
int param = 0;
int updateCount [] = null;
System.out.println ("\nExecute Statement and PreparedStatement Batch Updates");
System.out.println ( "-----------------------------------------------------");
// Load driver
loadDriver();