Oracle TimesTen Java

download Oracle TimesTen Java

of 110

Transcript of Oracle TimesTen Java

  • 8/12/2019 Oracle TimesTen Java

    1/110

    Oracle TimesTen

    In-Memory Database

    Java Developers andReference Guide

    Release 7.0

    B31681-01

  • 8/12/2019 Oracle TimesTen Java

    2/110

    Copyright 1996, 2007, Oracle. All rights reserved.

    ALL SOFTWARE AND DOCUMENTATION (WHETHER INHARD COPY OR ELECTRONIC FORM) ENCLOSED AND ONTHE COMPACT DISC(S) ARE SUBJECT TO THE LICENSEAGREEMENT.

    The documentation stored on the compact disc(s) may be printed by

    licensee for licensees internal use only. Except for the foregoing,no part of this documentation (whether in hard copy or electronicform) may be reproduced or transmitted in any form by any means,electronic or mechanical, including photocopying, recording, orany information storage and retrieval system, without the priorwritten permission of TimesTen Inc.

    Oracle, JD Edwards, PeopleSoft, Retek, TimesTen, the TimesTenicon, MicroLogging and Direct Data Access are trademarks or reg-istered trademarks of Oracle Corporation and/or its affiliates. Other

    names may be trademarks of their respective owners.The Programs (which include both the software and documenta-tion) contain proprietary information; they are provided under a li-cense agreement containing restrictions on use and disclosure andare also protected by copyright, patent, and other intellectual andindustrial property laws. Reverse engineering, disassembly, or de-compilation of the Programs, except to the extent required to obtaininteroperability with other independently created software or asspecified by law, is prohibited.

    The information contained in this document is subject to changewithout notice. If you find any problems in the documentation,please report them to us in writing. This document is not warrantedto be error-free. Except as may be expressly permitted in your li-cense agreement for these Programs, no part of these Programs maybe reproduced or transmitted in any form or by any means, elec-tronic or mechanical, for any purpose.

    February 2007

    Printed in the United States of America

  • 8/12/2019 Oracle TimesTen Java

    3/110

    iii

    Contents

    About this GuideTimesTen documentation . . . . . . . . . . . . . . . . . . . . . 1

    Background reading . . . . . . . . . . . . . . . . . . . . . . . 2

    Conventions used in this guide . . . . . . . . . . . . . . . . . . . 3

    Technical Support . . . . . . . . . . . . . . . . . . . . . . . . 5

    1 Configuring the Java Development EnvironmentInstalling TimesTen and the JDK . . . . . . . . . . . . . . . . . . 7

    Setting the Java Environment Variables. . . . . . . . . . . . . . . . 8

    Set CLASSPATH . . . . . . . . . . . . . . . . . . . . . . . 8

    Set the shared library path variable . . . . . . . . . . . . . . . . 9

    Set the THREADS_FLAG variable (UNIX only) . . . . . . . . . . 9

    Set the PATH variable . . . . . . . . . . . . . . . . . . . . . 11

    Compiling and Executing Java Applications . . . . . . . . . . . . . . 11

    About the TimesTen Java Demos . . . . . . . . . . . . . . . . . . 12About the TimesTen demo schema . . . . . . . . . . . . . . . . 12

    What the TimesTen demos do . . . . . . . . . . . . . . . . . . 13

    Compiling the TimesTen Java demos . . . . . . . . . . . . . . . 14

    Executing the TimesTen Java demos . . . . . . . . . . . . . . . 15Executing the level demos . . . . . . . . . . . . . . . . . . 15Executing the XlaLevel demos . . . . . . . . . . . . . . . . 16Problems executing the TimesTen Java demo programs . . . . . . 21Problems compiling the TimesTen Java demo program . . . . . . 21

    2 Working with TimesTen Data Stores

    Java Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 24Connecting to a TimesTen Data Store . . . . . . . . . . . . . . . . 24

    Load the TimesTen driver. . . . . . . . . . . . . . . . . . . . 25

    Create a connection URL for the data store . . . . . . . . . . . . . 25Specifying data store attributes in the connection URL . . . . . . 26

    Connect to the data store . . . . . . . . . . . . . . . . . . . . 26

    Disconnect from the data store . . . . . . . . . . . . . . . . . . 26

    Opening and closing a direct driver connection. . . . . . . . . . . . . 26

    Managing TimesTen Data . . . . . . . . . . . . . . . . . . . . . 28

    Calling SQL statements within Java applications . . . . . . . . . . 28Setting autocommit . . . . . . . . . . . . . . . . . . . . 28

    Preparing SQL statements . . . . . . . . . . . . . . . . . . 29Executing SQL statements . . . . . . . . . . . . . . . . . . 31Setting a timeout value for executing SQL statements . . . . . . . 33

  • 8/12/2019 Oracle TimesTen Java

    4/110

    iv Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Putting it all together: preparing and executing SQL . . . . . . . . 34

    Fetching multiple rows of data . . . . . . . . . . . . . . . . . . 35

    Executing multiple SQL statements in a batch . . . . . . . . . . . . 37

    Working with result sets . . . . . . . . . . . . . . . . . . . . 38

    Calling TimesTen built-in procedures. . . . . . . . . . . . . . . . . 39

    Managing Multiple Threads . . . . . . . . . . . . . . . . . . . . 41

    Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . 42

    About fatal errors, non-fatal errors, and warnings . . . . . . . . . . 42Handling fatal errors and recovery . . . . . . . . . . . . . . . 42Handling non-fatal errors . . . . . . . . . . . . . . . . . . 43About warnings . . . . . . . . . . . . . . . . . . . . . . 43

    Reporting errors and warnings . . . . . . . . . . . . . . . . . . 44

    Detecting and responding to specific errors . . . . . . . . . . . . . 46

    Rolling back failed transactions . . . . . . . . . . . . . . . . . 47

    3 Using JMS/XLA for Event ManagementJMS/XLA Concepts . . . . . . . . . . . . . . . . . . . . . . . 50

    How XLA reads records from the transaction log . . . . . . . . . . 50

    XLA and materialized views. . . . . . . . . . . . . . . . . . . 52XLA configuration file and topics . . . . . . . . . . . . . . . . 52

    XLA updates . . . . . . . . . . . . . . . . . . . . . . . . . 53

    XLA bookmarks . . . . . . . . . . . . . . . . . . . . . . . 54

    XLA acknowledgement modes . . . . . . . . . . . . . . . . . . 55Prefetching updates . . . . . . . . . . . . . . . . . . . . 56Acknowledging updates . . . . . . . . . . . . . . . . . . . 56

    XLA Demos . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    XlaLevel1 demo . . . . . . . . . . . . . . . . . . . . . . . 56

    JMS/XLA and Oracle GDK dependency . . . . . . . . . . . . . . . 56

    Connecting to XLA. . . . . . . . . . . . . . . . . . . . . . . . 57

    Monitoring Tables for Updates . . . . . . . . . . . . . . . . . . . 57

    Receiving and Processing Updates . . . . . . . . . . . . . . . . . . 58

    Processing updates . . . . . . . . . . . . . . . . . . . . . . 59

    Terminating an XLA Application . . . . . . . . . . . . . . . . . . 60

    Closing the connection . . . . . . . . . . . . . . . . . . . . . 61

    Deleting bookmarks . . . . . . . . . . . . . . . . . . . . . . 61

    Unsubscribing from a table . . . . . . . . . . . . . . . . . . . 61

    Using XLA as a Replication Mechanism . . . . . . . . . . . . . . . 62

    TargetDataStore error recovery . . . . . . . . . . . . . . . . . . 63

    4 Application TuningTuning Java applications. . . . . . . . . . . . . . . . . . . . . . 65

    Turn off autocommit mode . . . . . . . . . . . . . . . . . . . 65

  • 8/12/2019 Oracle TimesTen Java

    5/110

    v

    Choose a timeout interval . . . . . . . . . . . . . . . . . . . . 66

    Reduce contention . . . . . . . . . . . . . . . . . . . . . . . 66

    Choose the best method of locking . . . . . . . . . . . . . . . . 67Choose an appropriate lock level . . . . . . . . . . . . . . . 67Choose an appropriate isolation level . . . . . . . . . . . . . . 67

    Choose the appropriate logging options . . . . . . . . . . . . . . 68

    Prepare statements in advance . . . . . . . . . . . . . . . . . . 69

    Avoid unnecessary prepare operations . . . . . . . . . . . . . . . 69

    Use the batch update facility for executing multiple statements . . . . . 70

    Bulk fetch rows of TimesTen data. . . . . . . . . . . . . . . . . 71

    Size transactions appropriately . . . . . . . . . . . . . . . . . . 71

    Use durable commits appropriately . . . . . . . . . . . . . . . . 72

    Use the ResultSet.getString method sparingly . . . . . . . . . . . . 72

    Avoid data type conversions . . . . . . . . . . . . . . . . . . . 73

    Avoid transaction rollback . . . . . . . . . . . . . . . . . . . 73

    Avoid frequent checkpoints . . . . . . . . . . . . . . . . . . . 73

    Tuning JMS/XLA applications . . . . . . . . . . . . . . . . . . . 74

    Configure xlaPrefetch parameter . . . . . . . . . . . . . . . . . 74

    Batch calls to ttXlaAcknowledge . . . . . . . . . . . . . . . . . 74Increase log buffer size . . . . . . . . . . . . . . . . . . . . . 74

    Handling high event rates . . . . . . . . . . . . . . . . . . . . 74

    5 JDBC ReferenceSupported JDBC Interfaces. . . . . . . . . . . . . . . . . . . . . 77

    Support for interfaces in java.sql package . . . . . . . . . . . . . 77CallableStatement . . . . . . . . . . . . . . . . . . . . .78Connection . . . . . . . . . . . . . . . . . . . . . . . . 78DatabaseMetaData . . . . . . . . . . . . . . . . . . . . . 78Driver . . . . . . . . . . . . . . . . . . . . . . . . . . 78ParameterMetaData . . . . . . . . . . . . . . . . . . . .79PreparedStatement . . . . . . . . . . . . . . . . . . . . . 79ResultSet . . . . . . . . . . . . . . . . . . . . . . . . . 79ResultSetMetaData . . . . . . . . . . . . . . . . . . . . . 79Statement . . . . . . . . . . . . . . . . . . . . . . . .79

    Support for interfaces in javax.sql package . . . . . . . . . . . . . 80DataSource . . . . . . . . . . . . . . . . . . . . . . . . 80ConnectionPoolDataSource . . . . . . . . . . . . . . . . . 80PooledConnection . . . . . . . . . . . . . . . . . . . . .80XADataSource . . . . . . . . . . . . . . . . . . . . . . 80

    TimesTen Extensions to JDBC . . . . . . . . . . . . . . . . . . . 80

    TimesTenConnection. . . . . . . . . . . . . . . . . . . . . . 80getTtPrefetchClose . . . . . . . . . . . . . . . . . . . . . 81getTtPrefetchCount . . . . . . . . . . . . . . . . . . . . . 81

  • 8/12/2019 Oracle TimesTen Java

    6/110

    vi Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    isDataStoreValid . . . . . . . . . . . . . . . . . . . . . . 81setTtPrefetchClose . . . . . . . . . . . . . . . . . . . . . 81setTtPrefetchCount . . . . . . . . . . . . . . . . . . . . . 82

    TimesTenVendorCode . . . . . . . . . . . . . . . . . . . . . 82

    6 JMS/XLA ReferenceXLA MapMessage contents . . . . . . . . . . . . . . . . . . . . 83

    Update type . . . . . . . . . . . . . . . . . . . . . . . . 83

    XLA flags . . . . . . . . . . . . . . . . . . . . . . . . 85DML event data formats . . . . . . . . . . . . . . . . . . . . . . 86

    Table data . . . . . . . . . . . . . . . . . . . . . . . . . . 86

    Row data . . . . . . . . . . . . . . . . . . . . . . . . . . 87Context information . . . . . . . . . . . . . . . . . . . . 87

    DDL event data formats . . . . . . . . . . . . . . . . . . . . . . 87

    CREATE_TABLE . . . . . . . . . . . . . . . . . . . . . . . 88

    DROP_TABLE . . . . . . . . . . . . . . . . . . . . . . . . 89

    CREATE_INDEX . . . . . . . . . . . . . . . . . . . . . . .89

    DROP_INDEX . . . . . . . . . . . . . . . . . . . . . . . . 90

    ADD_COLUMNS. . . . . . . . . . . . . . . . . . . . . . . 91DROP_COLUMNS . . . . . . . . . . . . . . . . . . . . . . 92

    CREATE_VIEW . . . . . . . . . . . . . . . . . . . . . . . 93

    DROP_VIEW . . . . . . . . . . . . . . . . . . . . . . . .94

    CREATE_SEQ . . . . . . . . . . . . . . . . . . . . . . . . 94

    DROP_SEQ . . . . . . . . . . . . . . . . . . . . . . . . . 94

    TRUNCATE . . . . . . . . . . . . . . . . . . . . . . . . . 95

    Data type mapping . . . . . . . . . . . . . . . . . . . . . . . . 95

    Internationalization support . . . . . . . . . . . . . . . . . . . . 97

    JMS classes for event handling . . . . . . . . . . . . . . . . . . . 98

    JMS/XLA Replication API . . . . . . . . . . . . . . . . . . . . . 98

    TargetDataStore. . . . . . . . . . . . . . . . . . . . . . . . 98

    TargetDataStoreImpl . . . . . . . . . . . . . . . . . . . . . .99

    JMS message header fields . . . . . . . . . . . . . . . . . . . . . 99

    Index

  • 8/12/2019 Oracle TimesTen Java

    7/110

    1

    About this GuideOracle Oracle TimesTen In-Memory Database In-Memory Database is a high-performance, in-memory data manager that supports the ODBC and JDBCinterfaces. The examples and procedures in this guide use the JDBC interface.

    This guide is for application developers who use and administer OracleTimesTen In-Memory Database JDBC and for system administrators whoconfigure and manage the Oracle TimesTen In-Memory Database daemon.

    To work with this guide, you should understand how database systems work. Youshould also have knowledge of SQL (Structured Query Language) and JDBC(Java Database Connectivity). See Background reading on page 2if you arenot familiar with these interfaces.

    TimesTen documentationTimesTen documentation is available on the product distribution media and onthe Oracle Technology Network:

    http://www.oracle.com/technology/documentation/timesten_doc.html.Including this guide, the TimesTen documentation set consists of thesedocuments:

    Book Titles Description

    Oracle TimesTen In-Memory

    Database Installation Guide

    Contains information needed to install and configureOracle TimesTen In-Memory Database on allsupported platforms.

    Oracle TimesTen In-Memory

    Database Introduction

    Describes all the available features in the OracleTimesTen In-Memory Database.

    Oracle TimesTen In-Memory

    Database Operations Guide

    Provides information on configuring TimesTen andusing the ttIsql utility to manage a data store. Thisguide also provides a basic tutorial for TimesTen.

    Oracle TimesTen In-Memory

    Database C Developers and

    Reference Guideand theOracle TimesTen In-Memory

    Database Java Developers

    and Reference Guide

    Provide information on how to use the full set ofavailable features in Oracle TimesTen In-MemoryDatabase to develop and implement applications thatuse Oracle TimesTen In-Memory Database.

    http://www.oracle.com/technology/documentation/timesten_doc.htmlhttp://www.oracle.com/technology/documentation/timesten_doc.html
  • 8/12/2019 Oracle TimesTen Java

    8/110

    2 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Background readingFor a Java reference, see:

    Horstmann, Cay and Gary Cornell. Core Java(TM) 2, Volume I--Fundamentals (7th Edition) (Core Java 2). Prentice Hall PTR; 7 edition(August 17, 2004).

    A list of books about ODBC and SQL is in the Microsoft ODBC manualincluded in your developers kit. Your developers kit includes the appropriateODBC manual for your platform:

    Oracle TimesTen In-Memory

    Database API Reference

    Guide

    Describes all TimesTen utilities, procedures, APIs andprovides a reference to other features of TimesTen.

    Oracle TimesTen In-Memory

    Database SQL Reference

    Guide

    Contains a complete reference to all TimesTen SQLstatements, expressions and functions, includingTimesTen SQL extensions.

    Oracle TimesTen In-MemoryDatabase Error Messages

    and SNMP Traps

    Contains a complete reference to the TimesTen errormessages and information on using SNMP Traps withTimesTen.

    Oracle TimesTen In-Memory

    Database TTClasses Guide

    Describes how to use the TTClasses C++ API to usethe features available in Oracle TimesTen In-MemoryDatabase to develop and implement applications.

    TimesTen to TimesTen

    Replication Guide

    Provides information to help you understand howOracle TimesTen In-Memory Database Replicationworks and step-by-step instructions and examples thatshow how to perform the most commonly needed

    tasks.This guide is for application developers who use andadminister Oracle TimesTen In-Memory Database andfor system administrators who configure and manageOracle TimesTen In-Memory Database Replication.

    TimesTen Cache Connect to

    Oracle Guide

    Describes how to use Cache Connect to cache Oracledata in TimesTen data stores. This guide is fordevelopers who use and administer TimesTen forcaching Oracle data.

    Oracle TimesTen In-Memory

    Database TroubleshootingProcedures Guide

    Provides information and solutions for handling

    problems that may arise while developing applicationsthat work with TimesTen, or while configuring ormanaging TimesTen.

  • 8/12/2019 Oracle TimesTen Java

    9/110

    About this Guide 3

    Microsoft ODBC 3.0 Programmers Reference and SDK Guideprovides allrelevant information on ODBC for Windows developers.

    Microsoft ODBC 2.0 Programmers Reference and SDK Guide, includedonline in PDF format, provides information on ODBC for UNIX developers.

    For a conceptual overview and programming how-to of ODBC, see:

    Kyle Geiger.Inside ODBC. Redmond, WA: Microsoft Press. 1995.

    For a review of SQL, see:

    Melton, Jim and Simon, Alan R. Understanding the New SQL: A CompleteGuide. San Francisco, CA: Morgan Kaufmann Publishers. 1993.

    Groff, James R. / Weinberg, Paul N. SQL: The Complete Reference, SecondEdition. McGraw-Hill Osborne Media. 2002.

    For information about Unicode, see:

    The Unicode Consortium, The Unicode Standard, Version 5.0,Addison-Wesley Professional, 2006.

    The Unicode Consortium Home Page at http://www.unicode.org

    Conventions used in this guideTimesTen supports multiple platforms. Unless otherwise indicated, theinformation in this guide applies to all supported platforms. The term Windowsrefers to Windows 2000, Windows XP and Windows Server 2003. The termUNIX refers to Solaris, Linux, HP-UX, Tru64 and AIX.

    TimesTen documentation uses these typographical conventions:

    TimesTen documentation uses these conventions in command line examples anddescriptions:

    If you see... It means...

    code font Code examples, filenames, and pathnames.

    For example, the . odbc. i ni . or t t connect. i ni file.

    italic code

    font

    A variable in a code example that you must replace.

    For example:Dri ver=install_dir/ l i b/ l i btten. sl

    Replace install_dirwith the path of your OracleTimesTen In-Memory Database installation directory.

    If you see... It means...

    fixed width

    italics

    Variable; must be replaced with an appropriate value.

  • 8/12/2019 Oracle TimesTen Java

    10/110

    4 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    TimesTen documentation uses these variables to identify path, file and usernames:

    [ ] Square brackets indicate that an item in a command lineis optional.

    { } Curly braces indicated that you must choose one of theitems separated by a vertical bar ( | ) in a command line.

    | A vertical bar (or pipe) separates arguments that you mayuse more than one argument on a single command line.

    . . . An ellipsis (. . .) after an argument indicates that you mayuse more than one argument on a single command line.

    % The percent sign indicates the UNIX shell prompt.

    # The number (or pound) sign indicates the UNIX rootprompt.

    If you see... It means...

    install_dir The path that represents the directory where the currentrelease of Oracle TimesTen In-Memory Database isinstalled.

    TTinstance The instance name for your specific installation ofTimesTen. Each installation of TimesTen must beidentified at install time with a unique alphanumericinstance name. This name appears in the install path. Theinstance name giraffe is used in examples in this guide.

    bitsor bb Two digits, either 32 or 64, that represent either the 32-bitor 64-bit operating system.

    releaseor rr Two digits that represent the first two digits of the currentOracle TimesTen In-Memory Database release number,with or without a dot. For example, 60 or 7.0 representsOracle TimesTen In-Memory Database Release 7.0.

    jdk_version Two digits that represent the version number of themajor JDK release. Specifically, 14 represent JDK 1.4;5 represents JDK 5.

  • 8/12/2019 Oracle TimesTen Java

    11/110

    About this Guide 5

    Technical Support

    For information about obtaining technical support for TimesTen products, go tothe following Web address:

    http://www.oracle.com/support/contact.html

    t i mest en A sample name for the TimesTen instance administrator.You can use any legal user name as the TimesTenadministrator. On Windows, the TimesTen instanceadministrator must be a member of the Administratorsgroup. Each TimesTen instance can have a uniqueinstance administrator name.

    DSN The data source name.

    http://www.oracle.com/support/contact.htmlhttp://www.oracle.com/support/contact.html
  • 8/12/2019 Oracle TimesTen Java

    12/110

    6 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

  • 8/12/2019 Oracle TimesTen Java

    13/110

    7

    1Configuring the Java Development

    EnvironmentThis chapter describes how to install, configure, and test your TimesTenapplication development environment. It includes the following topics:

    Installing TimesTen and the JDK

    Setting the Java Environment Variables

    Compiling and Executing Java Applications

    About the TimesTen Java Demos

    Installing TimesTen and the JDKInstall and configure TimesTen for your environment, as described in the OracleTimesTen In-Memory Database Installation Guide, and the Java JDK, asdescribed in your Java installation guide. The topics of particular interest in theOracle TimesTen In-Memory Database Installation Guidewhen setting up a Javadevelopment environment include:

    Access Control

    JDK support

    Client/Server configurations

    Environment modifications

    After you have installed and configured TimesTen, create a data store DSN asdescribed in the Oracle TimesTen In-Memory Database Operations Guide. Thetopics of particular interest include:

    TimesTen JDBC driver

    User and system DSNs

    Data Manager and Client DSNs

    Thread programming with TimesTen

    Creating a DSN on UNIXor Creating a DSN on Windows

    http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/
  • 8/12/2019 Oracle TimesTen Java

    14/110

    8 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Setting the Java Environment Variables

    The environment variable settings for TimesTen are explained in Environmentmodificationsin the Oracle TimesTen In-Memory Database Installation Guide.This section provides more detail on those that impact the environment forTimesTen Java applications.

    On UNIX platforms, you can set all of the environment variables described inthis section by sourcing one of the following scripts:

    install_dir/ bi n/ t t Set Env. sh

    install_dir/ bi n/ t t Set Env. csh

    On Windows, you can either set the environment variables during installation orrun:

    install_dir\ bi n\ t tenv. bat

    The rest of this section describes values the environment variables are set to, aswell as how to set them manually, if necessary.

    Set CLASSPATH

    Java classes and class libraries are found on CLASSPATH. Before executing aJava program that loads any of the TimesTen JDBC drivers, the CLASSPATHenvironment variable must contain the class library file:

    install_dir/ l i b/ cl assesjdk_ver. j ar

    jdk_verindicates the version of the JDK that you are using. For example, forJDK 1.4, jdk_veris 14. For JDK 5.0, jdk_veris 5.

    Note: If more than one jar file is listed in the CLASSPATH, make sure theTimesTen jar file is listed first.

    On UNIX, CLASSPATH elements are separated by colon. For example:

    set CLASSPATH . : / opt / Ti mesTen/ t t70/ l i b/ t t j dbc14. j ar

    or

    setenv CLASSPATH . : / opt / Ti mesTen/ t t70/ l i b/ t t j dbc14. j ar

    On Windows, CLASSPATH elements are separated by semicolons. Also, onWindows, do not use quotes when setting the CLASSPATH environment variableeven if a directory pathname contains spaces.

    For example, this is correct:

    set CLASSPATH=. ; C: / Ti mesTen/ t t70/ l i b/ t t j dbc14. j ar

    This is incorrect:set CLASSPATH=. ; "C: / Ti mesTen/ t t70/ l i b/ t t j dbc14. j ar"

    http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/
  • 8/12/2019 Oracle TimesTen Java

    15/110

    Configuring the Java Development Environment 9

    If in doubt about the JDK version you have installed on your system, enter:

    > j ava - versi on

    If you are going to use the JMS/XLA interface described in Chapter 3, UsingJMS/XLA for Event Management, then you also need to add the following toyour CLASSPATH:

    install_dir/ l i b/ t i mestenj msxl a. j arinstall_dir/ 3rdpart y/ j ms1. 1/ l i b/ j ms. j ar

    For example, your CLASSPATH would look like:

    . : C: / Ti mesTen/ t t70/ l i b/ t t j dbc14. j ar : C: / Ti mesTen/ t t70/ l i b/t i mestenj msxl a. j ar : C: / Ti mesTen/ t t70/ 3rdparty/ j ms1. 1/ l i b/ j ms. j ar

    By default, JMS/XLA looks for a configuration file calledj msxl a. xml in thecurrent working directory. If you want to use another name or location for thefile, you need to specify it as part of the environment variable in theInitialContextclass and add the location to CLASSPATH. See XLAconfiguration file and topics on page 52for more information about thej msxl a. xml configuration file.

    Set the shared library path variableBefore running a java program that loads the TimesTen JDBC driver, the sharedl i brary path f or your systemenvironment variable must be set to includethe TimesTen install_dir/ l i b di rectory. The name of the variable usedfor the shared library path depends on the system used:

    See Shared library path environment variablein the Oracle TimesTen In-Memory Database Installation Guidefor details on setting the shared librarypath.

    Set the THREADS_FLAG variable (UNIX only)

    The TimesTen JDBC driver uses native threads; green threads are not supported.

    System Name of Variable

    Linux LD_LIBRARY_PATH

    Solaris LD_LIBRARY_PATH

    HPUX SHLIB_PATH or LD_LIBRARY_PATH

    AIX LIBPATH

    Windows PATH

    http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/http://install.pdf/
  • 8/12/2019 Oracle TimesTen Java

    16/110

    10 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    On some UNIX platforms, in order to use the native threads package, you mustset the environment variable THREADS_FLAG to native. How you set the flagdepends on your shell.

    In csh, the syntax is:

    set env THREADS_FLAG nati ve

  • 8/12/2019 Oracle TimesTen Java

    17/110

    Configuring the Java Development Environment 11

    In sh, the syntax is:

    THREADS_FLAG=nat i veexport THREADS_FLAG

    Set the PATH variable

    Make sure the executablesjavacandjavaare both on your executable searchpath, or will need to invoke them using absolute paths.

    Compiling and Executing Java ApplicationsTo compile a Java program, at your shell or command prompt use the command:

    j avac SourceFile.j ava

    The command generates the bytecode file SourceFile. cl assif the . j ava filecontains a public class. A . cl assfile is generated for all classes defined inSourceFile. j ava. By default the . cl ass files reside in the same directory asthe . j avasource files. To specify a different target directory for the . cl assfiles,use the command:

    j avac - d Directory SourceFile.j avaThe class name is the same as the filename prefix of its corresponding . cl assfile. To execute a Java program, at your shell or command prompt use thecommand:

    j ava ClassName

    ClassNameis the name of a class that contains a mai nmethod. This commandstarts the Java Virtual Machine (JVM) that will interpret and execute the Javabytecode in the . cl assfile and any other bytecode files that it is dependentupon.

    Example 1.1 To compile the l evel 1. j avademo and execute it using the demodata store,enter:

    > cd install_dir/ demo/ tutor i al / j ava

    > j avac l evel 1. j ava

    > tt I sql - f . . / dat f i l es/i nput 0. dat demo

    > j ava l evel 1 demo

  • 8/12/2019 Oracle TimesTen Java

    18/110

    12 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    About the TimesTen Java Demos

    Once you have configured your Java environment, you can confirm thateverything is set up correctly by compiling and running the TimesTen Java demoapplications in the install_dir/ demo/ tutor i al / j avadirectory.

    About the TimesTen demo schema

    The TimesTen Java demos are designed to work with the TimesTen demo

    schema, which simulates a simple order-processing database. You can populate adata store with the TimesTen demo schema by running the install_dir/ demo/tutor i al / dat f i l es/ i nput0. dat , as described in Executing the TimesTenJava demos on page 15. The i nput0. dat file creates the following tables:

    xyz.product

    xyz.inventory

    xyz.customer

    xyz.orders

    xyz.order_item

    The tables in the demo schema are organized and populated with data, as shownin Figure 1.1

    Figure 1.1 TimesTen Demo Schema

    xyz.customer

    ord_num cust_num when_placed when_shipped

    xyz.orders

    ord_num prod_num quantity

    xyz.order_Item

    xyz.product

    123

    34

    100110021003

    10081009

    sysdate2003-04-11 09:17:32.1480002003-03-09 08:15:12.100000

    sysdatesysdate

    NULLNULLNULL

    NULLNULL

    100210021003100310081009

    addressnamecust_num region

    1234

    FiberificsNatural Foods Co.Happy Food Inc.Nakamise

    123 any street5150 Johnson Rd4004 Happy Lane6-6-2 Nishi Shinjuku

    SouthWestNorthEast

    prod_num name price ship_weight description

    100101102103

    $4.50$1.94$2.76$1.50

    0.250.250.225.055

    Beef FlavorChicken FlavorGarlic extractOat bran

    Tasty artificial beef flavor crystalsMakes everything taste like chickenPure essence of garlicAll natural oat bran

    xyz.inventoryprod_num warehouse quantity

    100101102103

    10000500010004000

    LondonNew YorkGilroyGilroy

    Not for use in soft drinksNot for use in soft drinksKeeps vampires awayMay reduce cholesterol

    picture notes

    NULLNULLNULLNULL

    notes

    NULLNULLNULL

    NULLNULL

    102103101102102103

    60005004050030079

  • 8/12/2019 Oracle TimesTen Java

    19/110

    Configuring the Java Development Environment 13

    What the TimesTen demos do

    The TimesTen Java demos are named l evel 1. j ava, l evel 2. j ava,l evel 3. j ava, l evel 4. j ava, Xl aLevel 1. j ava, Xl aLevel 2. j ava, andXl aLevel 3. j ava. All of the l evel demos support both direct and clientconnections to the data store.

    The l evel 1demo uses the DriverManagerinterface to connect to a data storeand forms a prepared INSERT and SELECT statement to insert new customer

    data into the xyz. customer table and then view the contents of the table. Itexecutes the INSERT until all of the data in the i nput1. dat file is loaded intothe table, executes the SELECT, fetches and prints the result set to st dout anddisconnects from the data store.

    The l evel 2demo uses the DataSourceinterfaceto connect to a data store andforms prepared INSERT, UPDATE, DELETE, and SELECT statements to insert,update, delete, and view product data in the xyz.product table. It executes theINSERT until all of the data in the i nput2. dat file is loaded into the table. Itexecutes the DELETE to delete any duplicate product data and then the UPDATEto increase the price of the products in the table by 10%. It executes a ttCkptprocedure to checkpoint the data store to disk, executes the SELECT, fetches and

    prints the result set to st dout and then disconnects from the data store.

    The l evel 3demo uses the DataSourceinterface to connect to a data store andforms prepared statements to perform order processing operations on the orderdata in the i nput3. dat file. For each order item in the data file, the demoperforms the following transaction:

    INSERT the new order into the xyz.orders and xyz. order_i temtables.

    SELECT from the xyz. i nventorytable to check the available quantity of theordered item in the inventory.

    UPDATE the xyz. i nventorytable to debit the ordered item from theinventory.

    If there are not enough items in the inventory, the demo rolls back the entiretransaction and reports that there is insufficient inventory for the order. Finally,the demo checkpoints the data store to disk and disconnects.

    The l evel 4demo processes the same orders as l evel 3, only it uses multiplethreads and multiple connections to increase throughput.

    Both the l evel 1and l evel 2demos call the TimesTen ttOptUpdateStatsbuilt-in procedure to update the statistics for the customer and product tables. ThettOptUpdateStatsprocedure stores the statistics in the SYS.COL_STATSandSYS.TBL_STATStables for use by the TimesTen query optimizer to enable moreefficient query execution.

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.htmlhttp://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://sql.pdf/http://sql.pdf/http://sql.pdf/http://sql.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html
  • 8/12/2019 Oracle TimesTen Java

    20/110

    14 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    The Xl aLevel 1. j ava, Xl aLevel 2. j ava, and Xl aLevel 3. j ava demos use theJMS/XLA API described in Chapter 3, Using JMS/XLA for Event Managementto monitor and report on specific updates to the data store. The Xl aLevel 1. j avaand Xl aLevel 2. j ava demos monitor updates to the xyz. customer table. TheXl aLevel 3. j ava demo monitors updates to a user-specified table.

    Compil ing the TimesTen Java demos

    To compile the Java demos, go to the Java demo directory and run ANT on thebui l d. xml file. If you do not want to use ANT, use thej avaccommand tocompile each demo. For example:

    > cd / Ti mesTen/ t t70/ demo/ t utor i al / j ava> j avac *. j ava

  • 8/12/2019 Oracle TimesTen Java

    21/110

    Configuring the Java Development Environment 15

    Executing the TimesTen Java demos

    Prior to executing any of the Java demos, you must execute the SQL statementsin the i nput 0. dat file, as shown below, to build or rebuild the demo schema.Each demo requires that you specify a DSN name. The DSN can be for either adirect connection or client connection to the data store.

    Executing the level demos

    All of the level demos have the following command syntax:demoname [ - t ] [ - d | - c] {DSN}demoname - h | - hel p

    - h | - hel p pri nt usage and exi t- d connect usi ng di r ect dr i ver (def aul t )- c connect usi ng cl i ent dr i ver- t enabl e J DBC t raci ngDSN name of the data st ore

    Example 1.2 In this example, we execute the l evel 1and l evel 2demos using a direct driver

    connection to theDMdemodata store. We enable JDBC tracing when executingthe l evel 2demo. Last, we execute the l evel 3demo using a client connection tothe CSdemodata store.

    Note: Before executing each demo, you must execute the i nput0. dat file torebuild the demo schema on the data store.

    > tt I sql - f . . / dat f i l es/ i nput 0. dat DMdemo. . . . . . output> j ava l evel 1 DMdemo. . . . . . output> tt I sql - f . . / dat f i l es/ i nput 0. dat DMdemo

    . . . . . . output> j ava l evel 2 - t DMdemo. . . . . . output> tt I sql CS - f . . / dat f i l es/ i nput0. dat CSdemo. . . . . . output> j ava l evel 3 -c CSdemo. . . . . . output

    If you cannot connect to the data store, you may not have configured the DSNname that you are specifying. See Data source namesin the Oracle TimesTenIn-Memory Database Operations Guide.

    http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/
  • 8/12/2019 Oracle TimesTen Java

    22/110

    16 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Executing the XlaLevel demos

    Note: You only need to look at the XlaLevel demos if you are going to be usingthe JMS/XLA API described in Chapter 3, Using JMS/XLA for EventManagement.

    In JMS/XLA, the name of the data store and other parameters used by XLAapplications are specified in the form ofXLA topics, as described in XLA

    configuration file and topics on page 52. The XlaLevel demos obtain their XLAtopicsfrom thej msxl a. xml file located in the install_dir/ demo/ tutor i al /j avadirectory. The topics in thej msxl a. xml file are configured so that theXlaLevel demos use the predefined RunData_TTinstancedata store and otherdefault parameters. You can edit thej msxl a. xml file to specify other topics orchange the settings in the exiting topics.

    Note: The demos in this document use the predefined data store RunData_tt70.

    All of the XlaLevel demos accept an optional topic name.

    The syntax for executing Xl aLevel 1is:

    Xl aLevel 1 [topic]

    where topicdefaults to theLevel1Demotopic that is prespecified in thej msxl a. xml file.

    The syntax for executing Xl aLevel 2is:

    Xl aLevel 2 [topic [bookmark] ]

    where topicdefaults toLevel2Demoand bookmarkdefaults to bookmark.

    The syntax for executing Xl aLevel 3is:

    Xl aLevel 3 [topic [bookmark [table] ] ]

    where topicdefaults toLevel3Demo, bookmarkdefaults to bookmark, and tabledefaults to tbl.

    Prior to executing any of the Xl aLevel 1and Xl aLevel 2demos, you mustexecute the SQL statements in the i nput0. dat file to build or rebuild the demoschema. Both the Xl aLevel 1and Xl aLevel 2demos monitor changes to thexyz. customertable.

  • 8/12/2019 Oracle TimesTen Java

    23/110

    Configuring the Java Development Environment 17

    When running the Xl aLevel 1demo, you can make updates to the xyz. cust omer table by running the l evel 1. j avademo in a separate shell.

    Example 1.3 To run the Xl aLevel 1. j avademo with its default topic, in one shell enter:

    > tt I sql - f . . / dat f i l es/ i nput 0. dat RunData_tt 70. . . . . . output> j ava Xl aLevel 1

    . . . . . . detected changes to the xyz.customer tableIn another shell, enter:

    > j ava l evel 1 RunData_t t70. . . . . . output

    The output from the Xl aLevel 1demo shows the detected changes to thexyz. customertable.

    If you create a new topic in thej msxl a. xml file, you can specify that when youenter run the Xl aLevel 1. j avademo. For example, if you created a new topic,namedMyTopic, you would start the Xl aLevel 1. j avademo with:

    > j ava Xl aLevel 1 MyTopi c

    The Xl aLevel 2demo prompts you to enter changes to the xyz. customer table inthe form of SQL from the command line. It then displays the detected changes tothe table after you commit the transaction.

    Example 1.4 To run the Xl aLevel 2. j avademo with its default topic and bookmark, enter:

    > tt I sql - f . . / dat f i l es/ i nput0. dat RunData_tt 70. . . . . . output> j ava Xl aLevel 2+++ Usi ng def aul t topi c Level 2Demo and def aul t bookmark bookmark+++ create sessi on+++ create topi c+++ createDurabl eSubscri ber+++ usi ng connect i on st r i ng' DSN=RunData_t t70; Excl Access=0; Loggi ng=1;LogPurge=0; Overwr i t e=0'+++ connect i ng t oj dbc: t i mest en: di rect : DSN=RunDat a_t t70; Excl Access=0; Loggi ng=1; LogPurge=0; Overwr i te=0+++ t urni ng of f autocommi tYou can now enter SQL commands. You shoul d enterei ther DML (such as i nsert s, updat es, or del etes) ,or DDL ( such as CREATE SEQUENCE) .

  • 8/12/2019 Oracle TimesTen Java

    24/110

    18 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    For i nstance, t ry: create sequence s mi nval ue 1000 i nsert i nto xyz. customer val ues(s. nextVal , ' us' , ' Bob' , ' nowhere' ) commi tAf ter each SQL command you enter, the demo t r i esto get and di spl ay any J MS/XLA updates.Type "qui t " t o exi t the demo, or "hel p"to see t hi s message agai n.NOTE: autocommi t i s t urned of f , so you wi l lhave to enter "commi t " to see your updates.Enter SQL: creat e sequence s mi nval ue 1000+++ cr eate sequence s mi nval ue 1000Enter SQL: i nser t i nto xyz. customer val ues( s. nextVal , ' us' , ' Bob' , ' nowhere' )+++ i nsert i nto xyz. customer val ues(s. next Val , ' us' , ' Bob' , ' nowhere' )Enter SQL: i nser t i nto xyz. customer val ues( s. nextVal , ' us' , ' Bob' , ' nowhere' )+++ i nsert i nto xyz. customer val ues(s. next Val , ' us' , ' Bob' , ' nowhere' )Enter SQL: commi t+++ commi t>>> got a CREATE SEQUENCE message CYCLE=t rue I NCREMENT=1 MAX_VALUE=9223372036854775807 MI N_VALUE=1000 NAME=S OWNER=ASPI N __COMMI T=f al se __CONTEXT=( nul l ) __FI RST=t rue

    __REPL=f al se __TYPE=16 __mt yp=nul l __mver=1144080>>> got a I NSERT message ADDRESS=nowher e CUST_NUM=1000 NAME=Bob REGI ON=us __NULLS= __TYPE=10 __mtyp=nul l __mver=1146360>>> got a I NSERT message ADDRESS=nowher e CUST_NUM=1001 NAME=Bob REGI ON=us __COMMI T=t rue __NULLS= __TYPE=10 __mtyp=nul l __mver=1147248Enter SQL: qui t+++ cl eani ng up+++ Subscr i ber cl ose+++ Producer . cl ose+++ done

    +++ shut t i ng down. . .

  • 8/12/2019 Oracle TimesTen Java

    25/110

    Configuring the Java Development Environment 19

    The Xl aLevel 3demo prompts you to specify the table you wish to make changesto and to monitor. If the table doesnt exist in theRunData_tt70data store, it iscreated.

    Example 1.5 To run the Xl aLevel 3. j avademo with its default topic,Level3Demo; abookmark named bkmk, and to create a new table, named tbl, enter:

    > j ava Xl aLevel 3 Level 3Demo bkmk tbl

    +++ t opi c=Level 3Demo, bookmark=bkmk, t abl e=tblMay 11, 2005 3: 32:26 PMcom. t i mesten. dat aserver . j msxl a. Si mpl eI ni t i al ContextFactory get I ni t i al ContextI NFO: Usi ng conf i gurat i on f i l e j msxl a. xml+++ create sessi on+++ create topi cMay 11, 2005 3: 32: 27 PM com. t i mest en. dataserver . j msxl a. Dest i nat i onI mpl FI NE: Propert i es f or topi c Level 3Demo: {xl aPrefetch=100, name=Level 3Demo,connect i onStr i ng=DSN=RunData_t t 70}+++ createDurabl eSubscri berMay 11, 2005 3: 32: 27 PM com. t i mest en. dataserver . j msxl a. Xl aSubscr i ber FI NE: Maki ng XLA subscr i pti on, connst r=DSN=RunData_t t70, bookmark=bkmk,

    pref etch=100, ackMode=1 May 11, 2005 3:32: 27 PMcom. t i mesten. dataserver . j msxl a. MessageConsumerI mpl creat eXl aSubscri berFI NE: Creat i ng MessageConsumer wi t h connect i on st r i ng=DSN=RunData_t t 70,bookmark=bkmk May 11, 2005 3:32: 27 PMcom. t i mesten. dat aserver . j msxl a. Xl aSubscr i ber st artFI NE: St art i ng XLA subscri pt i on+++ usi ng connect i on st r i ng ' DSN=RunData_t t70'+++ connect i ng t o j dbc: t i mesten: di rect: DSN=RunData_t t70+++ t urni ng of f autocommi ttabl e tbl al ready exi sts+++ {cal l t tXl aSubscr i be( ' tbl ' , ' bkmk' )}You can now enter SQL commands. You shoul d enter ei ther DML ( such as i nsert s,updat es, or del etes) , or DDL ( such as CREATE SEQUENCE).For i nstance, t ry: create sequence s mi nval ue 1000 i nsert i nto tbl val ues(s. next Val ) cal l t tAppl i cat i onContext ( ' i nser ted somethi ng' ) commi tAf ter each SQL command you enter, the demo t r i es t o get and di spl ay any J MS/XLAupdat es.Type "qui t " t o exi t the demo, or "hel p"to see t hi s message agai n.NOTE: autocommi t i s t urned of f , so you wi l l have t o enter "commi t " t o see yourupdat es.Enter SQL: creat e sequence s mi nval ue 1000

    +++ cr eate sequence s mi nval ue 1000Enter SQL: i nser t i nto tbl val ues(s. nextVal )+++ i nsert i nto tbl val ues( s. nextVal )

  • 8/12/2019 Oracle TimesTen Java

    26/110

    20 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Enter SQL: cal l t tAppl i cat i onContext ( ' i nserted somet hi ng' )+++ cal l t tAppl i cat i onCont ext ( ' i nserted somet hi ng' )Enter SQL: commi t+++ commi t>>> got a CREATE TABLE message NAME=TBL OWNER=ASPI N _A_I NPRI MARYKEY=nul l _A_NULLABLE=nul l _A_OUTOFLI NE=nul l _A_PRECI SI ON=nul l _A_SCALE=nul l _A_SI ZE=nul l __COMMI T=nul l __FI RST=nul l __TYPE=nul l __mtyp=nul l __mver=nul l>>> got a CREATE SEQUENCE message CYCLE=t rue I NCREMENT=1 MAX_VALUE=9223372036854775807 MI N_VALUE=1000 NAME=S OWNER=ASPI N __COMMI T=f al se __CONTEXT=( nul l ) __FI RST=t rue __REPL=f al se __TYPE=16 __mt yp=nul l __mver=385368>>> got a I NSERT message A=1000 __NULLS=B __TYPE=10 __mtyp=nul l __mver =386576>>> got a COMMI T ONLY message __COMMI T=t rue __CONTEXT=i nserted somethi ng __FI RST=f al se __REPL=f al se __TYPE=13 __mtyp=nul l __mver=386880 Ent er SQL: cr eate i ndex i xon tbl (a)+++ create i ndex i x on tbl (a)Enter SQL: commi t+++ commi t

    >>> got a CREATE I NDEX message COLUMNS=A HASH_PAGES=0 I NDEX_METHOD=T I NDEX_TYPE=R I XNAME=I X TBLNAME=TBL TBLOWNER=ASPI N UNI QUE=f al se __COMMI T=t rue __CONTEXT=( nul l ) __FI RST=t rue __REPL=f al se __TYPE=3 __mtyp=nul l __mver =392904Enter SQL: drop i ndex i x+++ drop i ndex i xEnter SQL: i nser t i nto tbl val ues(s. nextVal )+++ i nsert i nto tbl val ues( s. nextVal )Enter SQL: i nser t i nto tbl val ues(s. nextVal )+++ i nsert i nto tbl val ues( s. nextVal )Enter SQL: updat e tbl set a=a+10

    +++ update tbl set a=a+10Enter SQL: commi t+++ commi t>>> got a DROP I NDEX message I NDEX_NAME=I X OWNER=ASPI N TABLE_NAME=TBL __COMMI T=f al se __CONTEXT=( nul l ) __FI RST=t rue __REPL=f al se __TYPE=4 __mtyp=nul l __mver =398776>>> got a I NSERT message A=1001 __NULLS=B __TYPE=10 __mtyp=nul l __mver =399472>>> got a I NSERT message A=1002 __NULLS=B __TYPE=10 __mtyp=nul l __mver =400112>>> got a UPDATE message

    A=1010 _A=1000 __NULLS=_B;B __TYPE=11 __UPDCOLS=A __mtyp=nul l __mver =400712

  • 8/12/2019 Oracle TimesTen Java

    27/110

    Configuring the Java Development Environment 21

    >>> got a UPDATE message A=1011 _A=1001 __NULLS=_B;B __TYPE=11 __UPDCOLS=A __mtyp=nul l __mver =401256>>> got a UPDATE message A=1012 _A=1002 __COMMI T=t rue __NULLS=_B; B __TYPE=11 __UPDCOLS=A __mtyp=nul l __mver=401800Enter SQL: qui t+++ cl eani ng up+++ Subscr i ber cl oseMay 11, 2005 3: 35: 04 PM com. t i mest en. dataserver . j msxl a. Xl aSubscr i bertabl eUnsubscr i beFI NE: Unsubscr i bi ng f romt abl e TBL+++ Producer . cl ose+++ done+++ shut t i ng down. . .

    Problems executing the TimesTen Java demo programs

    If you receive an error message like:

    j ava. l ang. Unsati sf i edLi nkError: no t t J dbcCS

    orj ava. l ang. Unsati sf i edLi nkError: no t t J dbc i n j ava. l i brary. path

    then you do not have LD_LIBRARY_PATH set properly. Find l i btt J dbc. soand put that directory on the LD_LIBRARY_PATH:

    set env LD_LI BRARY_PATH install_dir/ l i b

    Problems compiling the TimesTen Java demo program

    If you receive the error message:

    j ava. l ang. Cl assNotFoundExcept i on: com. t i mest en. j dbc. Ti mesTenDr i ver

    CLASSPATH is not set properly. Find the classes archive file and make sure thatit is on the CLASSPATH, for example:

    setenv CLASSPATH install_dir/ l i b/ tt j dbc14. j ar

    If you get a ClassNotFoundException for a class defined in one of the demos(such as level1), make sure the current directory is included in yourCLASSPATH. For example:

    setenv CLASSPATH install_dir/ l i b/ tt j dbc14. j ar: .

  • 8/12/2019 Oracle TimesTen Java

    28/110

    22 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

  • 8/12/2019 Oracle TimesTen Java

    29/110

    23

    2Working with TimesTen Data Stores

    This chapter describes the basic procedures for writing a Java application toaccess data in a TimesTen data store. Before attempting to write a TimesTenapplication, be sure you have completed the following prerequisite tasks:

    After you have successfully executed the TimesTen Java demos, yourdevelopment environment is set up correctly and ready for you to createapplications that accesses a TimesTen data store.

    Topics in this chapter are: Java Classes

    Connecting to a TimesTen Data Store

    Managing TimesTen Data

    Calling TimesTen built-in procedures

    Managing Multiple Threads

    Handling Errors

    Prerequisite Task What you do

    Create a TimesTen data store Follow the procedures described inChapter 1, Creating TimesTen DataStores in the Oracle TimesTen In-Memory Database Operations Guide

    Configure Java environment Follow the procedures described inSetting the Java EnvironmentVariables on page 8

    Compile and execute theTimesTen Java demos

    Follow the procedures described inAbout the TimesTen Java Demos on

    page 12

    http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/
  • 8/12/2019 Oracle TimesTen Java

    30/110

    24 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Java Classes

    Most TimesTen applications can be written using the supported Java classes andinterfaces listed in Chapter 5, JDBC Reference.

    You must import the standard JDBC packages in any java program that useJDBC:

    i mpor t j ava. sql . *;

    If you are going to make use of the DataSourceinterface, you must also importthe optional JDBC packages:

    i mpor t j avax. sql . *;

    Though you can accomplish most operations with the standard Java interfaces,TimesTen provides the following extensions to the Java standard.

    To use the TimesTen implementation of thejavax.sql.DataSourceinterface,import:

    i mport com. t i mesten. j dbc. DataSource;

    To use the TimesTen implementation of thejavax.sql.XADataSourceinterface,import:

    i mport com. t i mesten. j dbc. xa. TimesTenVendorCode;

    To use the TimesTen connection-based prefetch feature described in Fetchingmultiple rows of data on page 35, import:

    i mport com. t i mesten. sql . TimesTenConnection;

    See TimesTen Extensions to JDBC on page 80for more information on theseTimesTen extentions.

    Connecting to a TimesTen Data Store

    The Oracle TimesTen In-Memory Database Operations Guidedescribes how tocreate a DSN to define a connection to a TimesTen data store. The type of DSNyou create depends on whether your application connects directly to the datastore or connects by a client. If you intend to connect directly to the data store,create a DSN as described in Creating a DSN on UNIXor Creating a DSN onWindowsin the Oracle TimesTen In-Memory Database Operations Guide. Ifyou intend to create a client connection to the data store, create a DSN asdescribed in Creating and configuring Client DSNs on Windowsor Creatingand configuring Client DSNs on UNIXin the Oracle TimesTen In-MemoryDatabase Operations Guide.

    After you have created a DSN, the application can connect to the data store. This

    section describes how to create a JDBC connection to a data store using either theJDBC direct driver or the JDBC client driver.

    The operations described in this section are based on the l evel 1. j avademo.

    http://java.sun.com/j2se/1.4.2/docs/api/javax/sql/DataSource.htmlhttp://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://java.sun.com/j2se/1.4.2/docs/api/javax/sql/DataSource.html
  • 8/12/2019 Oracle TimesTen Java

    31/110

    Working with TimesTen Data Stores 25

    The procedures for connecting to a TimesTen data store are:

    Load the TimesTen driver

    Create a connection URL for the data store

    Connect to the data store

    Disconnect from the data store

    Putting it all together: preparing and executing SQL

    Load the TimesTen driver

    The TimesTen JDBC driver must be loaded before it is available for makingconnections with a TimesTen data store. The TimesTen JDBC driver is:

    com. t i mesten. j dbc. Ti mesTenDr i ver

    If you are using the DriverManagerinterface to connect to TimesTen, call theClass.forName()method to load the TimesTen JDBC driver. This methodcreates an instance of the TimesTen Driver and registers it with the drivermanager.

    If you are using the TimesTenDataSource interface, you do not need to call

    Class.forName().

    Example 2.1 To identify and load the TimesTen driver:

    Cl ass. f orName("com. t i mest en. j dbc. Ti mesTenDr i ver") ;

    Note: If the TimesTen JDBC driver is not loaded, an error is returned when theapplication attempts to connect to a TimesTen data store.

    Create a connection URL for the data store

    To create a JDBC connection, you need to specify a TimesTen connection URLfor the data store. The format of a TimesTen connection URL is:

    j dbc: t i mest en: {di rect | cl i ent}: dsn=DSNname; [DSNattributes; ]

    For example, to create a direct connection to the demodata store, the URL lookssimilar to the following:

    St r i ng URL = "j dbc: t i mest en: di rect : dsn=demo";

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/javax/sql/DataSource.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/javax/sql/DataSource.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)
  • 8/12/2019 Oracle TimesTen Java

    32/110

    26 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Specify ing data store attributes in the connection URL

    You can programmatically set or override the connection attributes in the DSNdescription by specifying attributes in the connection URL.

    For example, to set the LockLevelDSN attribute to 1, you could create a URLlike:

    St r i ng URL = "j dbc: t i mest en: di rect : dsn=demo;LockLevel =1";

    Connect to the data store

    After you have defined a URL, you can use either theDriverManager.getConnection()or TimesTenDataSource .getConnection()method to connect to the TimesTen data store.

    If you use the DriverManager.getConnection()method, specify the driver URLto connect to the data store:

    i mport java.sql.*;Connecti on con = Dr i verManager. getConnecti on(URL) ;

    To use the DataSource.getConnection()method, first create a DataSource.

    Then use the DataSource.setUrl()method to set the URL andDataSource.getConnection()to connect:

    i mport com. t i mesten. j dbc. Ti mesTenDataSource;

    Ti mesTenDataSource ds = new Ti mesTenDataSource( ) ;ds. setUr l ( URL);con = ds. getConnect i on( ) ;

    Either method returns a Connectionobject (conin this example) that you can useas a handle to the data store. See the l evel 1demo for an example on how to useDriverManager.getConnection()and the l evel 2and l evel 3demos forexamples of using DataSource.getConnection().

    Disconnect from the data store

    When you are finished accessing the TimesTen data store, call theConnection.close()method to close the connection to the data store.

    If an error has occurred, you may want to roll back the transaction beforedisconnecting from the data store. See Handling non-fatal errors on page 43and Rolling back failed transactions on page 47for more information.

    Opening and closing a direct driver connectionExample 2.2shows the general framework for an application that uses the

    DriverManager to create a direct driver connection to the demodata store;execute some SQL, and then close the connection. See the l evel 1. j avademofor a working example.

    http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#close()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.htmlhttp://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#close()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String)
  • 8/12/2019 Oracle TimesTen Java

    33/110

    Working with TimesTen Data Stores 27

    Example 2.2 String URL = "jdbc:timesten:dsn=demo";Connect i on con = nul l ;

    try {Cl ass. f orName("com. t i mest en. j dbc. Ti mesTenDr i ver") ;

    } catch (Cl assNotFoundExcept i on ex) {

    / / See Handl i ng Err ors on page 42}

    try {/ / Open a connect i on to Ti mesTencon = Dr i verManager. getConnecti on(URL) ;

    / / Report any SQLWarni ngs on the connect i on

    / / See Repor t i ng er r ors and warni ngs on page 44

    / / Do SQL operati ons

    / / See Managi ng Ti mesTen Dat a on page 28

    / / Cl ose t he connect i on to Ti mesTen

    con. cl ose( ) ;

    / / Handl e any errors} catch (SQLExcept i on ex) {

    / / See Handl i ng Er r ors on page 42}

  • 8/12/2019 Oracle TimesTen Java

    34/110

    28 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Managing TimesTen Data

    This section provides detailed information on working with data in a TimesTendata store. It includes the following topics:

    Calling SQL statements within Java applications

    Fetching multiple rows of data

    Executing multiple SQL statements in a batch

    Working with result sets

    Calling SQL statements within Java applications

    This section includes the following topics:

    Setting autocommit

    Preparing SQL statements

    Executing SQL statements

    Setting a timeout value for executing SQL statements

    Putting it all together: preparing and executing SQL

    Setting autocommit

    A TimesTen Connection has autocommit enabled by default. You can useConnection.setAutoCommit()to enable or disable autocommit. If autocommitis disabled (set to false), you must use Connection.commit()to manuallycommit transactions.

    For example, to set autocommit to off:

    con. setAut oCommi t ( f al se);

    / / Report any SQLWarni ngs on the connect i on

    / / See Repor t i ng er r ors and warni ngs on page 44

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#setAutoCommit(boolean)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#commit()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#commit()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#setAutoCommit(boolean)
  • 8/12/2019 Oracle TimesTen Java

    35/110

    Working with TimesTen Data Stores 29

    Preparing SQL statements

    SQL statements that are to be executed more than once should be prepared inadvance by calling the Connection.prepareStatement()method.

    For maximum performance, prepare parameterized statements. In TimesTen,SQL statements containing duplicate parameters are parsed such that onlydistinct parameter names are considered as separate parameters. Binding is basedon the position of the first occurrence of a parameter name. Each duplicate

    parameter occurrence is bound to the same value.Example 2.3shows how four separate INSERT statements can be substitutedwith a single parameterized statement.

    Example 2.3 Rather than execute a similar INSERT statement with different values:

    Stat ement . execute( "i nsert i nt o t1 val ues (1, 2) ") ;Stat ement . execute( "i nsert i nt o t1 val ues (3, 4) ") ;Stat ement . execute( "i nsert i nt o t1 val ues (5, 6) ") ;Stat ement . execute( "i nsert i nt o t1 val ues (7, 8) ") ;

    It is much more efficient to prepare a single parameterized INSERT statement

    and use PreparedStatement.set...()methods to set the row values before eachexecute:

    PreparedStatement pI ns =con. PreparedStatement ( "i nsert i nto t1 val ues ( ?, ?) ") ;

    con. commi t ( ) ;

    pI ns. set I nt (1, I nt eger . parseI nt (1) ) ;pI ns. set I nt (2, I nt eger . parseI nt (2) ) ;pI ns. executeUpdate() ;

    pI ns. set I nt (1, I nt eger . parseI nt (3) ) ;

    pI ns. set I nt (2, I nt eger . parseI nt (4) ) ;pI ns. executeUpdate() ;

    pI ns. set I nt (1, I nt eger . parseI nt (5) ) ;pI ns. set I nt (2, I nt eger . parseI nt (6) ) ;pI ns. executeUpdate() ;

    pI ns. set I nt (1, I nt eger . parseI nt (7) ) ;pI ns. set I nt (2, I nt eger . parseI nt (8) ) ;pI ns. executeUpdate() ;

    con. commi t ( ) ;pI ns. cl ose( ) ;

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#prepareStatement(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#prepareStatement(java.lang.String)
  • 8/12/2019 Oracle TimesTen Java

    36/110

    30 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Note: After preparing SQL statements, call Connection.commit()in order torelease the locks held by the prepare and to allow the query plan to persist. Whenyou have finished executing a prepared statement, call thePreparedStatement.close()method to release the resources associated with thestatement.

    TimesTen shares prepared statements automatically once they have been

    committed. For example, if two or more separate connections to the data storeeach prepare the same statement, then the 2nd, 3rd, and nth prepare returns veryquickly because TimesTen remembers the first prepared statement.

    Example 2.4 In this example, we prepare three identical parameterized INSERT statements forthree separate connections. The first prepared INSERT for connection con1isshared with the con2and con3connections and speeds up thepIns2andpIns3prepare operations:

    Connect i on con1;Connect i on con2;Connect i on con3;

    . . . . .PreparedStatement pI ns1 = con1.prepareSt atement

    ( "i nsert i nt o t1 val ues (?, ?)") ;con1. commi t ( ) ;

    PreparedStatement pI ns2 = con2.prepareSt atement( "i nsert i nt o t1 val ues (?, ?)") ;

    con2. commi t ( ) ;

    PreparedStatement pI ns3 = con3.prepareSt atement( "i nsert i nt o t1 val ues (?, ?)") ;

    con3. commi t ( ) ;

    Note: All tuning options, such as join ordering, indexes and locks must matchfor the statement to be shared. Also, if the prepared statement references a temptable, it will only be shared within a single connection.

    Note: TimesTen also supports prepared statement pooling forPooledConnections, as specified in the JDBC 3.0 specification. You canconfigure the maximum size of the pool by settingObservableConnectionDS.setMaxStatements(). Once set, this value should notbe changed.

    See Prepare statements in advance on page 69for a general discussion of theperformance benefits of preparing SQL statements in advance.

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#commit()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#close()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#close()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#close()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#commit()
  • 8/12/2019 Oracle TimesTen Java

    37/110

    Working with TimesTen Data Stores 31

    Executing SQL statements

    Chapter 6, Working with Data in a TimesTen Data Store in the OracleTimesTen In-Memory Database Operations Guidedescribes how to use SQL tomanage data in a TimesTen data store. This section describes how to use theConnection.createStatement(), Statement.executeUpdate(), andStatement.executeQuery()methods to execute a SQL statement within a Javaapplication.

    Unless statements are prepared in advance, as described in Preparing SQLstatements, use the Statementexecute methods, such as Statement.execute(),Statement.executeUpdate(), or Statement.executeQuery(), depending on thenature of your SQL statement and any returned result set.

    For SQL statements that are a prepared in advance, use the PreparedStatementexecutemethods, such as PreparedStatement.execute(),PreparedStatement.executeUpdate(), or PreparedStatement.executeQuery().

    The execute()method returns True if there is a result set (for example, on. aSELECT) or False if there is no result set (for example, on an INSERT,UPDATE, or DELETE). The executeUpdate()method returns the number of

    rows affected. For example, when executing an INSERT statement, theexecuteUpdate()method returns the number of rows inserted. TheexecuteQuery()method returns a result set, so it should only be called when aresult set is expected (for example, when executing a SELECT).

    Note: See Working with result sets on page 38for details about what you needto know when working with result sets generated by TimesTen.

    Example 2.5 to use the Statement.executeUpdate() method to execute an INSERTinto thexyz.customer table, enter:

    Connect i on con;Statement st mt ;. . . . . .try {

    st mt = con. createStatement ( ) ;

    i nt numRows = st mt . executeUpdate( "i nsert i nto xyz. cust omerval ues" + "( 40, ' West' , ' Bi g Di sh' , ' 123 Si gnal St . ' ) ; ") ;

    }catch (SQLExcept i on ex) { . . . . .}

    http://operations.pdf/http://operations.pdf/http://operations.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#createStatement()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#execute()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#executeUpdate()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#executeQuery()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://sql.pdf/http://sql.pdf/http://operations.pdf/http://operations.pdf/http://operations.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#executeQuery()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#executeUpdate()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#execute()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Connection.html#createStatement()
  • 8/12/2019 Oracle TimesTen Java

    38/110

    32 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Example 2.6 In this example, we use a Statement.executeQuery()method to execute aSELECTon thexyz.customer table and display the returned ResultSet:

    Statement st mt ;. . . . . .try {

    Resul t Set rs = st mt . executeQuery("sel ect cust _num, regi on, " +"name, address f romxyz. cust omer ; ") ;

    System. out . pr i nt l n( "Fetchi ng resul t set . . . ") ;whi l e ( r s. next ( ) ) {

    System. out . pr i nt l n( "\ n Customer number : " + rs. get I nt (1) ) ;System. out . pr i nt l n( " Regi on: " + rs. getSt r i ng(2) ) ;System. out . pr i nt l n( " Name: " + rs. getSt r i ng(3) ) ;System. out . pr i nt l n( " Address: " + rs. getSt r i ng(4) ) ;}

    }catch (SQLExcept i on ex) { ex. pr i ntStackTrace( ) ;}

    Example 2.7 In this example, we use a PreparedStatement.executeQuery()method toexecute a prepared SELECTstatement and display the returned ResultSet:

    PreparedSt atement pSel =con. prepareStatement ( "sel ect cust _num, " +"regi on, name, address " +"f romxyz. customer; ") ;

    con. commi t ( ) ;

    try {Resul t Set rs = pSel . executeQuery() ;

    whi l e ( r s. next ( ) ) {Syst em. out . pr i nt l n( "\ n Customer number: " + rs. get I nt (1) ) ;System. out . pr i nt l n( " Regi on: " + rs. getSt r i ng(2) ) ;System. out . pr i nt l n( " Name: " + rs. get St r i ng( 3) ) ;System. out . pr i nt l n( " Address: " + rs. get St r i ng(4) ) ;

    }}catch (SQLExcept i on ex) { ex. pr i ntStackTrace( ) ;}

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)http://sql.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#executeQuery()http://sql.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://sql.pdf/http://sql.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#executeQuery()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
  • 8/12/2019 Oracle TimesTen Java

    39/110

    Working with TimesTen Data Stores 33

    Setting a timeout value for executing SQL statements

    In TimesTen you can set the DSN attribute SqlQueryTimeoutto specify thequery timeout period for all connections. If you set SqlQueryTimeoutin theDSN specification, its value becomes the default value for all subsequentconnections to the data store.

    You can override the SqlQueryTimeoutvalue for the current connection bycalling the Statement.setQueryTimeout()method to set the time limit in

    seconds for which the data store should execute SQL queries. In TimesTen, oncethe timeout trigger fires it indicates to the executing query that it must timeout.Since there can be a lag in the time that it takes the timeout message to get to thequery, the actual time it takes for the query to end is approximately the time ittakes for the time out message to get to the query plus the timeout valuespecified.

    The Statement.setQueryTimeout()method works only when the SQL statementis actively executing. A timeout does not occur during the commit or rollbackphase of the operation. For those transactions that do a large number of updates,deletes, or inserts, the commit or rollback phases may take a long time tocomplete. During that time the timeout value is ignored.

    Note: The LockWaitand SqlQueryTimeoutsettings in TimesTen are separatefeatures and can have separate values. TimesTen checks for both lock timeoutand SQLQueryTimeout values. TimesTen examines all threads and wakes up anysleeping process that has either a lock timeout or a SQL query timeout, andindicates the appropriate SqlQueryTimeoutvalue to any executing thread. Ifboth a LockWaittimeout value and a SqlQueryTimeoutvalue are specified, thelesser of the two values causes a timeout first.

    http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#setQueryTimeout(int)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#setQueryTimeout(int)http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#setQueryTimeout(int)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#setQueryTimeout(int)
  • 8/12/2019 Oracle TimesTen Java

    40/110

    34 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Putting i t all together: preparing and executing SQL

    In this example, we prepare INSERT and SELECT statements; execute theINSERT twice; execute the SELECT, and print the returned result set. For aworking example, see the l evel 1. j avademo.

    Connect i on con;Statement st mt ;

    / / Di sabl e auto-commi tcon. setAut oCommi t ( f al se);

    / / Report any SQLWarni ngs on the connect i on

    / / See Repor t i ng er r ors and warni ngs on page 44

    / / Prepare a parameteri zed I NSERT and a SELECT StatementPreparedSt atement pI ns = con. prepareStat ement ( "i nsert i ntoxyz. customer val ues ( ?, ?, ?, ?) ") ;

    PreparedStatement pSel = con. prepareStatement( "sel ect cust _num, regi on, name, " +"address f romxyz. cust omer") ;

    / / Prepare i s a transact i on; must commi t to rel ease l ockscon. commi t ( ) ;

    / / Data f or f i r st I NSERT st at ementpI ns. set I nt (1, I nt eger . parseI nt (100) ) ;pI ns. set St ri ng( 2, N ) ;pI ns.setStr i ng(3, Fi beri f i cs) ;pI ns. set St r i ng( 4, 123 any str eet ) ;

    / / Execute the I NSERT statementpI ns. executeUpdate() ;

    / / Data for second I NSERT statementpI ns. set I nt (1, I nt eger . parseI nt (101) ) ;pI ns. set St ri ng( 2, N ) ;pI ns. set St r i ng( 3, Natural Foods Co. ) ;pI ns. set St r i ng( 4, 5150 J ohnson Rd ) ;

    / / Execute the I NSERT statementpI ns. executeUpdate() ;

    / / Commi t the i nsert scon. commi t ( ) ;

    / / Done wi th I NSERTs, so cl ose the prepared st atementpI ns. cl ose( ) ;

  • 8/12/2019 Oracle TimesTen Java

    41/110

    Working with TimesTen Data Stores 35

    / / Report any SQLWarni ngs on the connect i onreportSQLWarni ngs( con. getWarni ngs( ) ) ;CheckI f StopI sRequested( ) ;

    / / Execute the prepared SELECT st atementResul tSet rs = pSel . execut eQuery() ;

    System. out . pr i nt l n( "Fetchi ng resul t set . . . ") ;whi l e ( r s. next ( ) ) {

    System. out . pr i nt l n( "\ n Customer number: " + rs. get I nt ( 1) ) ;System. out . pr i nt l n( " Regi on: " + rs. get St r i ng(2) ) ;System. out . pr i nt l n( " Name: " + rs. getSt r i ng(3) ) ;System. out . pr i nt l n( " Address: " + rs. getSt r i ng( 4) ) ;

    }

    / / Cl ose t he resul t set .rs. cl ose() ;

    / / Commi t the sel ect - yes sel ects need to be commi t ted toocon. commi t ( ) ;

    / / Cl ose t he sel ect st atement - we' re done wi th i tpSel . cl ose( ) ;

    Fetching mult iple rows of data

    Fetching multiple rows of data from a TimesTen data store can increase theperformance of an application that connects to a data store set with readcommitted isolation.

    You can specify the number of rows to be prefetched by:

    Calling the Statement.setFetchSize()and ResultSet.setFetchSizemethods.

    These are the standard JDBC calls, but the limitation is that they only affectone statement at a time.

    Calling the TimesTenConnection.setTtPrefetchCount()method or by usingthe ttIsqlprefetchcount command. These enable a TimesTen extension thatestablishes prefetch on a connection level so that all of the statements on theconnection use the same prefetch setting.

    This section describes the connection-level prefetch implemented in TimesTen.

    Note: You can use the TimesTen prefetch count extension only with direct-linked applications.

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#setFetchSize(int)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#setFetchSize(int)http://tt_ref.pdf/http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#setFetchSize(int)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#setFetchSize(int)
  • 8/12/2019 Oracle TimesTen Java

    42/110

    36 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    When the prefetch count is set to 0, TimesTen uses a default value, depending onthe Isolationlevel you have set for the data store. In read committed isolationmode, the default prefetch value is 5. In serializable isolation mode, the default is128. The default prefetch value is the optimum setting for most applications.Generally, a higher value may result in better performance for larger result sets,at the expense of slightly higher resource use.

    To disable prefetch, set the prefetch count to 1.

    Call TimesTenConnection.getTtPrefetchCount()to check the current prefetchvalue.

    Example 2.8 In this example, we use the ttIsqlprefetchcountcommand to set the prefetchcount for the connection to 6:

    > tt I sql RunDat a_t t51Command > pref etchcount 6;

    Example 2.9 In this example, we use setTtPrefetchCount()to set the prefetch count to 10 andthen use getTtPrefetchCount()to return the prefetch count in the count variable.

    Ti mesTenConnect i on con =(Ti mesTenConnect i on) Dr i verManager . getConnect i on(ur l ) ;

    / / set pref ech count t o 10 f or thi s connecti oncon. setTtPref et chCount (10) ;

    / / Return the pref etch count to the count var i abl e.i nt count = con. getTtPref etchCount ( ) ;

    http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/
  • 8/12/2019 Oracle TimesTen Java

    43/110

    Working with TimesTen Data Stores 37

    Executing multiple SQL statements in a batch

    You can improve performance by calling the addBatch() and executeBatch()methods for the Statementand PreparedStatementobjects.

    For Statementobjects, a batch typically consists of a set of INSERT or UPDATEstatements. Statements that return result sets are not allowed in a batch. A SQLstatement is added to a batch by calling the addBatch()method. The set of SQLstatements associated with a batch are executed through the executeBatch()method. For example:

    / / t urn of f aut ocommi tconn. setAutoCommi t ( f al se);

    Statement st mt = conn. createStatement ( ) ;st mt . addBatch("I NSERT I NTO empl oyees VALUES (1000, ' J oeJ ones' ) ") ;st mt . addBatch("I NSERT I NTO departments VALUES ( 260, ' Shoe' ) ") ;st mt . addBatch("I NSERT I NTO emp_dept VALUES ( 1000, 260)") ;

    / / submi t a batch of updat e commands f or execut i oni nt [ ] updateCounts = st mt . executeBat ch( ) ;conn. commi t ( ) ;

    For PreparedStatementobjects, a batch consists of a set of prepared statementinput parameters. Prepared statement parameters are added to the batch byexecuting set calls followed by the addBatch()call. The batch is executed viathe executeBatch()method. For example:

    / / t urn of f aut ocommi tconn. setAutoCommi t ( f al se);

    PreparedStatement st mt = conn. prepareStatement ("I NSERT I NTO empl oyees VALUES ( ?, ?) ") ;

    / / f i rst set of parametersstmt . set I nt (1, 2000) ;

    stmt . set St r i ng( 2, "Kel l y Kauf mann") ;st mt . addBatch( ) ;

    / / second set of parametersstmt . set I nt (1, 3000) ;stmt . set St r i ng( 2, "Bi l l Barnes") ;st mt . addBatch( ) ;

    / / submi t the batch for execut i on. Check update countsi nt [ ] updateCounts = st mt . executeBat ch( ) ;conn. commi t ( ) ;

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html
  • 8/12/2019 Oracle TimesTen Java

    44/110

    38 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Working with result sets

    In addition to queries, some methods and built-in procedures return TimesTendata in the form of a ResultSetobject. This section describes what you need toknow when using ResultSetobjects from TimesTen.

    TimesTen does not support multiple open ResultSetobjects per statement.TimesTen cannot return multiple ResultSetobjects from a single Statementobject without first closing the current result set.

    TimesTen does not support holdable cursors. You cannot specify theholdability of a result set, i.e. whether a cursor can remain open after it has

    been committed.

    ResultSetobjects are not scrollable or updatable, so you cannot specifyResultSet.TYPE_SCROLL_SENSITIVEorResultSet.CONCUR_UPDATABLE.

    Use the ResultSet.closemethod to close ResultSetobjects as soon as you aredone with them.

    Calling ResultSet.getStringis more costly performance-wise if theunderlying data type is not a string. Because Java strings are immutable,

    ResultSet.getStringmust allocate space for a new string each time it is called.This makes ResultSet.getString one of the costlier calls in JDBC. Do not useResultSet.getStringto retrieve primitive numeric types, like Byte or Integer,unless it is absolutely necessary. For example, it is much faster to callResultSet.getInton an integer column.

    JDBC ignores the setting for the ConnectionCharacterSetattribute. Itreturns data in UTF-16 encoding.

    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#TYPE_SCROLL_SENSITIVEhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#CONCUR_UPDATABLEhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#close()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getInt(int)http://tt_ref.pdf/http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getInt(int)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#CONCUR_UPDATABLEhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#TYPE_SCROLL_SENSITIVEhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#close()http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html
  • 8/12/2019 Oracle TimesTen Java

    45/110

    Working with TimesTen Data Stores 39

    Calling TimesTen buil t-in procedures

    Chapter 3, Built-In Procedures in the Oracle TimesTen In-Memory DatabaseAPI Reference Guidedescribes the TimesTen built-in procedures that extendstandard ODBC functionality. You can execute a TimesTen built-in procedureusing the CallableStatementinterface.

    To execute the built-in procedure, use the format:

    Cal l abl eSt atement . execute( "{ Cal l Procedure }")

    To prepare and execute a built-in procedure, use the format:

    Cal l abl eSt atement cStmt ;cStmt = con. prepareCal l ( "{ Cal l Procedure }");cStmt . execute( ) ;

    For built-in procedures that return results, you can use theResultSetget*()methods to retrieve the data from the returned ResultSet, as demonstrated inExample 2.11.

    Note: See Working with result sets on page 38for details about what you needto know when working with result sets generated by TimesTen.

    Example 2.10 To call the ttCkptprocedure to initiate a fuzzy checkpoint, enter:

    Connect i on con;Cal l abl eSt atement cStmt ;. . . . . . .cStmt = con. prepareCal l ( "{ Cal l t t Ckpt }") ;cStmt . execute( ) ;con. commi t ( ) ; / / commi t the t ransact i on

    http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/CallableStatement.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://tt_ref.pdf/http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getString(java.lang.String)http://java.sun.com/j2se/1.4.2/docs/api/java/sql/CallableStatement.html
  • 8/12/2019 Oracle TimesTen Java

    46/110

    40 Oracle TimesTen In-Memory Database Java Developers and Reference Guide

    Example 2.11 This example calls the ttDataStoreStatus procedure and prints out the returnedresult set.