0% found this document useful (0 votes)
25 views84 pages

JDBC

Uploaded by

Ramirsky Saint
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views84 pages

JDBC

Uploaded by

Ramirsky Saint
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

c-treeSQL

JDBC Developer's Guide


c-treeSQL
JDBC Developer's Guide
Copyright © 1992-2014 FairCom Corporation. All rights reserved. No part of this publication may be stored in a retrieval system, or transmitted
in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the prior written permission of FairCom
Corporation. Printed in the United States of America.

Information in this document is subject to change without notice.

Trademarks
c-treeACE, c-treeRTG, c-treeAMS, c-tree Plus, c-tree, r-tree, FairCom and FairCom’s circular disc logo are trademarks of FairCom, registered
in the United States and other countries.
The following are third-party trademarks: AMD and AMD Opteron are trademarks of Advanced Micro Devices, Inc. Macintosh, Mac OS, and
Xcode are trademarks of Apple Inc., registered in the U.S. and other countries. Embarcadero, the Embarcadero Technologies logos and all
other Embarcadero Technologies product or service names are trademarks, service marks, and/or registered trademarks of Embarcadero
Technologies, Inc. and are protected by the laws of the United States and other countries. Business Objects and the Business Objects logo,
BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services
mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects Software Ltd. Business
Objects is an SAP company. DBstore is a trademark of Dharma Systems, Inc. HP and HP-UX are registered trademarks of the
Hewlett-Packard Company. AIX, IBM, OS/2, OS/2 WARP, Power 6 and POWER7 are trademarks or registered trademarks of International
Business Machines Corporation in the United States, other countries, or both. Intel, Itanium, Pentium and Xeon are trademarks or registered
trademarks of Intel Corporation or its subsidiaries in the United States and other countries. LynuxWorks, LynxOS and BlueCat are registered
trademarks of LynuxWorks, Inc. Microsoft, the .NET logo, MS-DOS, Windows, Windows Mobile, Windows NT, Windows Server, Windows
Vista, Visual Basic, and Visual Studio, are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or
other countries. Novell, NetWare, and SUSE are registered trademarks of Novell, Inc., in the United States and other countries. Oracle and
Java are registered trademarks of Oracle and/or its affiliates. QNX and Neutrino are registered trademarks of QNX Software Systems Ltd. in
certain jurisdictions. Red Hat and the Shadow Man logo are registered trademarks of Red Hat, Inc. in the United States and other countries,
used with permission. SCO and SCO Open Server are trademarks or registered trademarks of The SCO Group, Inc. in the U.S.A. and other
countries. SGI and IRIX are registered trademarks of Silicon Graphics, Inc., in the United States and/or other countries worldwide. UNIX and
UnixWare are registered trademarks of The Open Group in the United States and other countries. Linux is a trademark of Linus Torvalds in
the United States, other countries, or both. Python and PyCon are trademarks or registered trademarks of the Python Software Foundation.
All other trademarks, trade names, company names, product names, and registered trademarks are the property of their respective holders.

FairCom welcomes your comments on this document and the software it describes. Send comments using the contact form:
www.faircom.com/contact (http://www.faircom.com/contact).

Portions © 1987-2014 Dharma Systems, Inc. All rights reserved. This software or web site utilizes or contains material that is © 1994-2007
DUNDAS DATA VISUALIZATION, INC. and its licensors, all rights reserved.
Portions Copyright © 1995-2013 Jean-loup Gailly and Mark Adler.
1/13/2015
Contents
Introduction .......................................................................................................................................................... 1
1.1 Overview ................................................................................................................................................... 1
1.2 JDBC Architecture .................................................................................................................................... 1
1.3 Types of JDBC Drivers ............................................................................................................................. 2
JDBC-ODBC Bridge Drivers ..................................................................................................................... 2
Native-Method Drivers .............................................................................................................................. 3
Network-Protocol All-Java Drivers ............................................................................................................ 3
Native-Protocol All-Java Drivers (c-treeSQL JDBC Driver) ...................................................................... 3
1.4 JDBC Compared to ODBC ....................................................................................................................... 3

Quick Tour ............................................................................................................................................................ 5


2.1 Introductory Tutorial .................................................................................................................................. 6
Init ............................................................................................................................................................. 7
Define ....................................................................................................................................................... 8
Manage ..................................................................................................................................................... 9
Done ....................................................................................................................................................... 11
Additional Resources .............................................................................................................................. 12
2.2 Relationships .......................................................................................................................................... 13
Init ........................................................................................................................................................... 15
Define ..................................................................................................................................................... 16
Manage ................................................................................................................................................... 19
Done ....................................................................................................................................................... 23
Additional Resources .............................................................................................................................. 24
2.3 Record/Row Locking............................................................................................................................... 25
Init ........................................................................................................................................................... 27
Define ..................................................................................................................................................... 28
Manage ................................................................................................................................................... 29
Done ....................................................................................................................................................... 32
Additional Resources .............................................................................................................................. 33
2.4 Transaction Processing .......................................................................................................................... 34
Init ........................................................................................................................................................... 35
Define ..................................................................................................................................................... 36
Manage ................................................................................................................................................... 39
Done ....................................................................................................................................................... 44
Additional Resources .............................................................................................................................. 45

Basic JDBC Driver Operations ......................................................................................................................... 47


3.1 Introduction ............................................................................................................................................. 47
3.2 Required Java Environment ................................................................................................................... 47
3.3 Setting Up the JDBC Driver: Web Server ............................................................................................. 47
Copying JDBC Driver and Applet Class Files ........................................................................................ 48
Creating a Web Page That Invokes the Applet ...................................................................................... 48
3.4 Setting Up the JDBC Driver: Application Server .................................................................................. 48
Copying JDBC Driver Files to the Application Server (If Necessary) ..................................................... 49
Setting Environment Variables ............................................................................................................... 49
Running the Sample Application ............................................................................................................ 49
3.5 Connecting to a Database ...................................................................................................................... 49
Load the JDBC Driver Using Class.forName ......................................................................................... 50
Connect to the JDBC Driver Using DriverManager.GetConnection ....................................................... 50
An Example Connection ......................................................................................................................... 51
Connection Pooling Support in JDBC..................................................................................................... 51

www.faircom.com
All Rights Reserved
iii
Table of Contents

3.6 Managing Transactions Explicitly to Improve Performance ................................................................... 52


3.7 Query Timeout Options........................................................................................................................... 53
3.8 Driver Socket SEND/RECV Timeout ...................................................................................................... 53
3.9 JDBC Version Information ...................................................................................................................... 53

JDBC Conformance Notes ................................................................................................................................ 55


4.1 Supported Data Types ............................................................................................................................ 55
4.2 Return Values for DatabaseMetaData Methods ..................................................................................... 56
4.3 Error Messages ...................................................................................................................................... 66

Glossary .................................................................................................................................................................. 67

Index ........................................................................................................................................................................ 75

FairCom Corporation
Copyright 2015 FairCom Corporation
iv
FairCom Typographical Conventions
Before you begin using this guide, be sure to review the relevant terms and typographical
conventions used in the documentation.
The following formatted items identify special information.

Formatting convention Type of Information


Bold Used to emphasize a point or for variable expressions such as
parameters
CAPITALS Names of keys on the keyboard. For example, SHIFT, CTRL, or
ALT+F4

FairCom Terminology FairCom technology term


FunctionName() c-treeACE Function name
Parameter c-treeACE Function Parameter
Code Example Code example or Command line usage
utility c-treeACE executable or utility
filename c-treeACE file or path name
CONFIGURATION KEYWORD c-treeACE Configuration Keyword
CTREE_ERR c-treeACE Error Code

www.faircom.com
All Rights Reserved
v
Chapter 1

Introduction

1.1 Overview
The c-treeACE SQL JDBC Driver provides access to c-treeACE SQL environments from applications
that support the JDBC 4.0 API (and requires JRE/JDK 1.6).
JDBC allows applications to connect to any database using the same set of Java interfaces. Those
interfaces allow programs to embed standard Structured Query Language (SQL) statements that
update and retrieve data in the database.
Because the Java interfaces and SQL syntax are independent of any particular database
implementation, JDBC makes it feasible for applications to connect to different database
environments without any modification.

1.2 JDBC Architecture


JDBC insulates Java applications from variations in database access implementations through the
JDBC API, a set of class libraries distributed as a standard part of core Java. Instead of using calls to
vendor-specific interfaces, JDBC applications use the JDBC API.
The JDBC API is distributed as the package java.sql and is included with the Java JDK (Version 1.6
or later), so any environment that supports a recent Java compiler can be used to develop JDBC
applications.
Calls to the JDBC API are managed by the JDBC driver manager. The JDBC driver manager can
support multiple drivers connecting to different databases. When an application tries to connect to a
particular database, the driver manager loads the appropriate JDBC driver and routes subsequent
calls through the driver.
A JDBC driver is a database-specific software that receives calls from the JDBC driver manager,
translates them into a form that the database can process, and returns data to the application.

www.faircom.com
All Rights Reserved
1
Chapter 1
Introduction

The following figure shows the different components of the JDBC architecture.
Figure 1: JDBC Architecture

1.3 Types of JDBC Drivers


JDBC drivers can either be entirely written in Java so that they can be downloaded as part of an
applet, or they can be implemented using native methods to bridge to existing database access
libraries.
JavaSoft defines four different types of JDBC drivers, as noted in the previous figure and outlined in
the following sections.

JDBC-ODBC Bridge Drivers


Type 1 drivers translate calls to JDBC methods into calls to Microsoft Open Database Connectivity
(ODBC) functions. Bridge drivers allow JDBC applications immediate access to database connectivity
provided by the existing array of ODBC drivers.
Both the JavaSoft JDK and Microsoft Java SDK include JDBC-ODBC bridge drivers.
ODBC architecture requires that the ODBC driver manager and (typically) the ODBC drivers
themselves be loaded on each client system. The requirement for software resident on client systems
means that JDBC-ODBC bridge drivers will not work with Java applets run from an Internet browser.
Browsers do not allow applets to run another program on the client to which they are downloaded. (In
general, JDBC-ODBC bridge drivers will not work in environments that restrict Java applications from
reading and writing files or running other programs.)
JDBC-ODBC bridge drivers are still useful in corporate networks, or for use by application server
code written in Java in a 3-tier architecture. In such an environment, the application server has
intermediary software, such as Blue Lobster’s Aptivity, that receives requests from browsers and
other Internet applications. The intermediary software in turn calls the JDBC driver manager when it
receives a database request.

FairCom Corporation
Copyright 2015 FairCom Corporation
2
c-treeSQL
JDBC Developer's Guide

Native-Method Drivers
Type 2 drivers contain Java code that calls “native” C or C++ methods already implemented by
database vendors.
Like an ODBC driver, a native-method driver must be installed on each client or server that uses it,
and thus has the same limitations as the JDBC-ODBC bridge drivers. A typical use of native-method
drivers is on application servers.

Network-Protocol All-Java Drivers


Type 3 drivers are completely written in Java. They translate JDBC calls into a database-independent
network protocol which is in turn translated to a DBMS protocol by middleware on a network server.
This type of driver can thus connect many Java clients to many different databases. The specific
protocol used depends on the vendor.
Type 3 drivers are the most flexible since they do not require any driver software resident on client
systems and can allow a single driver to provide access to multiple databases.

Native-Protocol All-Java Drivers (c-treeSQL JDBC Driver)


Type 4 drivers are also written completely in Java, but do not rely on middleware. They convert JDBC
calls directly into the network protocol used by a particular database. This approach allows a direct
call from the client system to the database server. Also, since there is no client-resident software, it
also is practical for Internet applications.
Type 4 drivers provide the best performance.
The c-treeACE SQL JDBC Driver is a Type 4 driver.

1.4 JDBC Compared to ODBC


Generally speaking, JDBC is to Java what Microsoft’s Open Database Connectivity (ODBC) interface
is to the C language. Both JDBC and ODBC:
 Provide a vendor-independent API that allows the same application to connect to different
vendors’ databases and retrieve and update data using standard SQL statements.
 Adopt the architecture of imposing a driver manager between applications and vendor-supplied
drivers that translate between the standard API and a vendor’s proprietary implementation.
 Are based on the X/Open SQL call-level interface specification.
JDBC proponents cite these advantages of JDBC over ODBC:
 JDBC applications enjoy the platform-independence of Java, which lends itself to Internet
applications. ODBC applications must, at a minimum, be recompiled to run on a different
operating-system/hardware combination.
 JDBC does not require software on each client system, which also recommends it for Internet
applications.
 JDBC is much simpler and easier to learn than ODBC.
 JDBC is not primarily targeted for PC application development, which makes for faster
implementation outside the Windows environment.

www.faircom.com
All Rights Reserved
3
Chapter 2

Quick Tour

www.faircom.com
All Rights Reserved
5
Chapter 2
Quick Tour

2.1 Introductory Tutorial


..\sdk\sql.jdbc\tutorials\JDBC_Tutorial1.java
This tutorial will take you through the basic use of the c-treeACE SQL JDBC Interface.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and You’re Done() !

Tutorial #1: Introductory - Simple Single Table


We wanted to keep this program as simple as possible. This program does the following:
 Initialize() - Connects to the c-treeACE Database Engine.
 Define() - Defines and creates a "customer master" (custmast) table/file.
 Manage() - Adds a few rows/records; Reads the rows/records back from the database;
displays the column/field content; and then deletes the rows/records.
 Done() - Disconnects from c-treeACE Database Engine.
Note our simple mainline:
import java.sql.*;
import java.io.*;

public class JDBC_Tutorial1 {


static Connection conn;
static Statement stmt;
//
// main()
//
// The main() function implements the concept of "init, define, manage
// and you're done..."
//
public static void main (String[] args)
throws java.io.IOException
{

Initialize();
Define();
Manage();
Done();

System.out.print("\nPress <ENTER> key to exit . . .");


System.in.read();
System.exit(0);
}
We suggest opening the source code with your own editor.

Continue now to review these four steps.

FairCom Corporation
Copyright 2015 FairCom Corporation
6
c-treeSQL
JDBC Developer's Guide

Init

First we need to open a connection to a database by providing the c-treeACE Database Engine with a
user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
private static void Initialize ()
{
System.out.println("INIT");

try
{
// load the driver
Class.forName ("ctree.jdbc.ctreeDriver");

// connect to server
System.out.println("\tLogon to server...");
conn = DriverManager.getConnection ("jdbc:ctree:6597@localhost:ctreeSQL", "ADMIN",
"ADMIN");

// create a statement handle


stmt = conn.createStatement();
}
catch (SQLException e)
{
Handle_Exception(e);
}
catch (Exception e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
7
Chapter 2
Quick Tour

Define

The Define() step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the table for containing a list of existing customers
//
private static void Define ()
{
System.out.println("DEFINE");

try
{
// create table
System.out.println("\tCreate table...");
stmt.executeUpdate("CREATE TABLE custmast (" +
"cm_custnumb CHAR(4), " +
"cm_custzipc CHAR(9), " +
"cm_custstat CHAR(2), " +
"cm_custrtng CHAR(1), " +
"cm_custname VARCHAR(47), " +
"cm_custaddr VARCHAR(47), " +
"cm_custcity VARCHAR(47))"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
8
c-treeSQL
JDBC Developer's Guide

Manage

The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// This function performs simple record functions of add, delete and gets
//
private static void Manage ()
{
System.out.println("MANAGE");

// delete any existing records


Delete_Records();

// populate the table with data


Add_Records();

// display contents of table


Display_Records();
}

//
// Delete_Records()
//
// This function deletes all the records in the table
//
private static void Delete_Records ()
{
System.out.println("\tDelete records...");

try
{
stmt.executeUpdate("DELETE FROM custmast");
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_Records()
//
// This function adds records to a table in the database from an
// array of strings
//
private static void Add_Records ()
{
System.out.println("\tAdd records...");

www.faircom.com
All Rights Reserved
9
Chapter 2
Quick Tour

String data[] = {
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
};

try
{
// add one record at time to table
for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO custmast VALUES " + data[i]);
}
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Display_Records()
//
// This function displays the contents of a table.
//
private static void Display_Records ()
{
System.out.print("\tDisplay records...");

try
{
// execute a query statement
ResultSet rs = stmt.executeQuery ("SELECT * FROM custmast");

// fetch and display each individual record


while (rs.next()) {
System.out.println("\n\t\t" + rs.getString(1) + " " + rs.getString(5));
}
rs.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
10
c-treeSQL
JDBC Developer's Guide

Done

When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
private static void Done ()
{
System.out.println("DONE");

try
{
stmt.close();
// logout
System.out.println("\tLogout...");
conn.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
11
Chapter 2
Quick Tour

Additional Resources

We encourage you to explore the additional resources listed here:


 Complete source code for this tutorial can be found in JDBC_Tutorial1.java in your installation
directory, within the 'sdk\sql.jdbc\tutorials' directory for your platform.
Example for the Windows platform:
C:\FairCom\V10.x.x\win32\sdk\sql.jdbc\tutorials\JDBC_Tutorial1.java.
 Additional documentation may be found on the FairCom Web site at: www.faircom.com

FairCom Corporation
Copyright 2015 FairCom Corporation
12
c-treeSQL
JDBC Developer's Guide

2.2 Relationships
..\sdk\sql.jdbc\tutorials\JDBC_Tutorial2.java
Now we will build some table/file relationships using the c-treeACE SQL JDBC Interface.
This tutorial will advance the concepts introduced in the first tutorial by expanding the number of
tables. We will define key columns/fields and create specific indices for each table to form a relational
model database.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and You’re Done() !

Tutorial #2: Relational Model and Indexing


Here we add a bit more complexity, introducing multiple tables, with related indices in order to form a
simple "relational" database simulating an Order Entry system. Here is an overview of what will be
created:

 Initialize() - Connects to the c-treeACE Database Engine.


 Define() - Defines and creates the "custmast", "custordr", "ordritem" and the "itemmast"
tables/files with related indices.
 Manage() - Adds some related rows/records to all tables/files. Then queries the database.
 Done() - Disconnects from c-treeACE Database Engine.
Note our simple mainline:
import java.sql.*;
import java.io.*;

public class JDBC_Tutorial2 {


static Connection conn;
static Statement stmt;
//
// main()
//
// The main() function implements the concept of "init, define, manage
// and you're done..."
//
public static void main (String[] args)
throws java.io.IOException
{
Initialize();
Define();

www.faircom.com
All Rights Reserved
13
Chapter 2
Quick Tour

Manage();
Done();

System.out.print("\nPress <ENTER> key to exit . . .");


System.in.read();
System.exit(0);
}
We suggest opening the source code with your own editor.

Continue now to review these four steps.

FairCom Corporation
Copyright 2015 FairCom Corporation
14
c-treeSQL
JDBC Developer's Guide

Init

First we need to open a connection to a database by providing the c-treeACE Database Engine with a
user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
private static void Initialize ()
{
System.out.println("INIT");

try
{
// load the driver
Class.forName ("ctree.jdbc.ctreeDriver");

// connect to server
System.out.println("\tLogon to server...");
conn = DriverManager.getConnection ("jdbc:ctree:6597@localhost:ctreeSQL", "ADMIN",
"ADMIN");

// create statement handles


stmt = conn.createStatement();
}
catch (SQLException e)
{
Handle_Exception(e);
}
catch (Exception e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
15
Chapter 2
Quick Tour

Define

The Define() step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the tables
//
private static void Define ()
{
System.out.println("DEFINE");

Create_CustomerMaster_Table();
Create_CustomerOrders_Table();
Create_OrderItems_Table();
Create_ItemMaster_Table();
}

//
// Create_CustomerMaster_Table()
//
// Create the table CustomerMaster
//
private static void Create_CustomerMaster_Table ()
{
// define table CustomerMaster
System.out.println("\ttable CustomerMaster");

try
{
stmt.executeUpdate("CREATE TABLE custmast (" +
"cm_custnumb CHAR(4), " +
"cm_custzipc CHAR(9), " +
"cm_custstat CHAR(2), " +
"cm_custrtng CHAR(1), " +
"cm_custname VARCHAR(47), " +
"cm_custaddr VARCHAR(47), " +
"cm_custcity VARCHAR(47))"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}

try
{
stmt.executeUpdate("CREATE UNIQUE INDEX cm_custnumb_idx ON custmast (cm_custnumb)");
}
catch (SQLException e)
{

FairCom Corporation
Copyright 2015 FairCom Corporation
16
c-treeSQL
JDBC Developer's Guide

Handle_Exception(e);
}
}

//
// Create_CustomerOrders_Table()
//
// Create the table CustomerOrders
//
private static void Create_CustomerOrders_Table ()
{
// define table CustomerOrders
System.out.println("\ttable CustomerOrders");

try
{
stmt.executeUpdate("CREATE TABLE custordr (" +
"co_ordrdate DATE, " +
"co_promdate DATE, " +
"co_ordrnumb CHAR(6), " +
"co_custnumb CHAR(4))"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}

try
{
stmt.executeUpdate("CREATE UNIQUE INDEX co_ordrnumb_idx ON custordr (co_ordrnumb)");
stmt.executeUpdate("CREATE INDEX co_custnumb_idx ON custordr (co_custnumb)");
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Create_OrderItems_Table()
//
// Create the table OrderItems
//
private static void Create_OrderItems_Table ()
{
// define table OrderItems
System.out.println("\ttable OrderItems");

try
{
stmt.executeUpdate("CREATE TABLE ordritem (" +
"oi_sequnumb SMALLINT, " +
"oi_quantity SMALLINT, " +
"oi_ordrnumb CHAR(6), " +
"oi_itemnumb CHAR(5))"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}

try
{
stmt.executeUpdate("CREATE UNIQUE INDEX oi_ordrnumb_idx ON ordritem (oi_ordrnumb,
oi_sequnumb)");
stmt.executeUpdate("CREATE INDEX oi_itemnumb_idx ON ordritem (oi_itemnumb)");
}

www.faircom.com
All Rights Reserved
17
Chapter 2
Quick Tour

catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Create_ItemMaster_Table()
//
// Create the table ItemMaster
//
private static void Create_ItemMaster_Table ()
{
// define table ItemMaster
System.out.println("\ttable ItemMaster");

try
{
stmt.executeUpdate("CREATE TABLE itemmast (" +
"im_itemwght INTEGER, " +
"im_itempric MONEY, " +
"im_itemnumb CHAR(5), " +
"im_itemdesc VARCHAR(47))"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}

try
{
stmt.executeUpdate("CREATE UNIQUE INDEX im_itemnumb_idx ON itemmast (im_itemnumb)");
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
18
c-treeSQL
JDBC Developer's Guide

Manage

The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// Populates table and perform a simple query
//
private static void Manage ()
{
System.out.println("MANAGE");

// populate the tables with data


Add_CustomerMaster_Records();
Add_CustomerOrders_Records();
Add_OrderItems_Records();
Add_ItemMaster_Records();

// perform a query:
// list customer name and total amount per order

// name total
// @@@@@@@@@@@@@ $xx.xx

// for each order in the CustomerOrders table


// fetch order number
// fetch customer number
// fetch name from CustomerMaster table based on customer number
// for each order item in OrderItems table
// fetch item quantity
// fetch item number
// fetch item price from ItemMaster table based on item number
// next
// next

System.out.println("\n\tQuery Results");

try
{

ResultSet rs = stmt.executeQuery (
"SELECT cm_custname, SUM(im_itempric * oi_quantity) " +
"FROM custmast, custordr, ordritem, itemmast " +
"WHERE co_custnumb = cm_custnumb AND co_ordrnumb = oi_ordrnumb AND oi_itemnumb =
im_itemnumb " +
"GROUP BY cm_custnumb, cm_custname");

// read resultset
while (rs.next())
{
// fetch customer name
String custname = rs.getString(1);

// fetch item price

www.faircom.com
All Rights Reserved
19
Chapter 2
Quick Tour

float total = rs.getFloat(2);

System.out.println("\t\t" + custname + "\t" + total);


}

rs.close();

}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_CustomerMaster_Records()
//
// This function adds records to table CustomerMaster from an
// array of strings
//
private static void Add_CustomerMaster_Records ()
{
System.out.println("\tAdd records in table CustomerMaster...");

String data[] = {
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
};

Delete_Records("custmast");

try
{
// add one record at time to table
for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO custmast VALUES " + data[i]);
}
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_CustomerOrders_Records()
//
// This function adds records to table CustomerOrders from an
// array of strings
//
private static void Add_CustomerOrders_Records ()
{
System.out.println("\tAdd records in table CustomerOrders...");

String data[] = {
"('09/01/2002','09/05/2002','1','1001')",
"('09/02/2002','09/06/2002','2','1002')"
};

Delete_Records("custordr");

try
{
// add one record at time to table
for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO custordr VALUES " + data[i]);

FairCom Corporation
Copyright 2015 FairCom Corporation
20
c-treeSQL
JDBC Developer's Guide

}
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_OrderItems_Records()
//
// This function adds records to table OrderItems from an
// array of strings
//
private static void Add_OrderItems_Records ()
{
System.out.println("\tAdd records in table OrderItems...");

String data[] = {
"(1,2,'1','1')",
"(2,1,'1','2')",
"(3,1,'1','3')",
"(1,3,'2','3')"
};

Delete_Records("ordritem");

try
{
// add one record at time to table
for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO ordritem VALUES " + data[i]);
}
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_ItemMaster_Records()
//
// This function adds records to table ItemMaster from an
// array of strings
//
private static void Add_ItemMaster_Records ()
{
System.out.println("\tAdd records in table ItemMaster...");

String data[] = {
"(10,19.95,'1','Hammer')",
"(3, 9.99,'2','Wrench')",
"(4, 16.59,'3','Saw')",
"(1, 3.98,'4','Pliers')"
};

Delete_Records("itemmast");

try
{
// add one record at time to table
for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO itemmast VALUES " + data[i]);
}
}
catch (SQLException e)
{
Handle_Exception(e);

www.faircom.com
All Rights Reserved
21
Chapter 2
Quick Tour

}
}

//
// Delete_Records()
//
// This function deletes all the records in a tables
//
private static void Delete_Records (String table)
{
System.out.println("\tDelete records...");

try
{
stmt.executeUpdate("DELETE FROM " + table);
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
22
c-treeSQL
JDBC Developer's Guide

Done

When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
private static void Done ()
{
System.out.println("DONE");

try
{
stmt.close();
// logout
System.out.println("\tLogout...");
conn.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
23
Chapter 2
Quick Tour

Additional Resources

We encourage you to explore the additional resources listed here:


 Complete source code for this tutorial can be found in JDBC_Tutorial2.java in your installation
directory, within the 'sdk\sql.jdbc\tutorials' directory for your platform.
Example for the Windows platform:
C:\FairCom\V10.x.x\win32\sdk\sql.jdbc\tutorials\JDBC_Tutorial2.java.
 Additional documentation may be found on the FairCom Web site at: www.faircom.com

FairCom Corporation
Copyright 2015 FairCom Corporation
24
c-treeSQL
JDBC Developer's Guide

2.3 Record/Row Locking


..\sdk\sql.jdbc\tutorials\JDBC_Tutorial3.java
Now we will explore row/record locks using the c-treeACE SQL JDBC Interface.
The functionality for this tutorial focuses on inserting/adding rows/records, then updating a single
row/record in the customer master table under locking control. The application will pause after a
LOCK is placed on a row/record. Another instance of this application should then be launched, which
will block, waiting on the lock held by the first instance. Pressing the <Enter> key will enable the first
instance to proceed. This will result in removing the lock thereby allowing the second instance to
continue execution. Launching two processes provides a visual demonstration of the effects of
locking and a basis for experimentation on your own.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and you’re Done() !

Tutorial #3: Locking


Here we demonstrate the enforcement of data integrity by introducing record/row "locking".
 Initialize() - Connects to the c-treeACE Database Engine.
 Define() - Defines and creates a "customer master" (custmast) table/file.
 Manage() - Adds a few rows/records; Reads the rows/records back from the database; displays
the column/field content. Then demonstrates an update operation under locking control, and a
scenario that shows a locking conflict.
 Done() - Disconnects from c-treeACE Database Engine.
Note our simple mainline:
import java.sql.*;
import java.io.*;

public class JDBC_Tutorial3 {


static Connection conn;
static Statement stmt;
//
// main()
//
// The main() function implements the concept of "init, define, manage
// and you're done..."
//
public static void main (String[] args)
throws java.io.IOException
{
Initialize();
Define();
Manage();
Done();

System.out.print("\nPress <ENTER> key to exit . . .");


System.in.skip(1);
System.in.read();
System.exit(0);
}
We suggest opening the source code with your own editor.

www.faircom.com
All Rights Reserved
25
Chapter 2
Quick Tour

Continue now to review these four steps.

FairCom Corporation
Copyright 2015 FairCom Corporation
26
c-treeSQL
JDBC Developer's Guide

Init

First we need to open a connection to a database by providing the c-treeACE Database Engine with a
user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
private static void Initialize ()
{
System.out.println("INIT");

try
{
// load the driver
Class.forName ("ctree.jdbc.ctreeDriver");

// connect to server
System.out.println("\tLogon to server...");
conn = DriverManager.getConnection ("jdbc:ctree:6597@localhost:ctreeSQL", "ADMIN",
"ADMIN");

// disable commit after each single SQL statement


conn.setAutoCommit(false);

// create a statement handle


stmt = conn.createStatement();
}
catch (SQLException e)
{
Handle_Exception(e);
}
catch (Exception e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
27
Chapter 2
Quick Tour

Define

The Define() step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the table for containing a list of existing customers
//
private static void Define ()
{
System.out.println("DEFINE");

try
{
// create table
System.out.println("\tCreate table...");
stmt.executeUpdate("CREATE TABLE custmast (" +
"cm_custnumb CHAR(4), " +
"cm_custzipc CHAR(9), " +
"cm_custstat CHAR(2), " +
"cm_custrtng CHAR(1), " +
"cm_custname VARCHAR(47), " +
"cm_custaddr VARCHAR(47), " +
"cm_custcity VARCHAR(47))"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}

try
{
stmt.executeUpdate("CREATE UNIQUE INDEX cm_custnumb_idx ON custmast (cm_custnumb)");
}
catch (SQLException e)
{
Handle_Exception(e);
}

try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
28
c-treeSQL
JDBC Developer's Guide

Manage

The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// This function performs record adds and updates using locking
//
private static void Manage ()
{
System.out.println("MANAGE");

// delete any existing records


Delete_Records();

// populate the table with data


Add_CustomerMaster_Records();

// display contents of table


Display_Records();

// update a record under locking control


Update_CustomerMaster_Record();

// display again after update and effects of lock


Display_Records();
}

//
// Delete_Records()
//
// This function deletes all the records in the table
//
private static void Delete_Records ()
{
System.out.println("\tDelete records...");

try
{
stmt.executeUpdate("DELETE FROM custmast");
}
catch (SQLException e)
{
Handle_Exception(e);
}
try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);

www.faircom.com
All Rights Reserved
29
Chapter 2
Quick Tour

}
}

//
// Add_CustomerMaster_Records()
//
// This function adds records to table CustomerMaster from an
// array of strings
//
private static void Add_CustomerMaster_Records ()
{
System.out.println("\tAdd records...");

String data[] = {
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
};

try
{
// add one record at time to table
for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO custmast VALUES " + data[i]);
}
}
catch (SQLException e)
{
Handle_Exception(e);
}
try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Display_Records()
//
// This function displays the contents of a table.
//
private static void Display_Records ()
{
System.out.print("\tDisplay records...");

try
{
// execute a query statement
ResultSet rs = stmt.executeQuery ("SELECT * FROM custmast");

// fetch and display each individual record


while (rs.next()) {
System.out.println("\n\t\t" + rs.getString(1) + " " + rs.getString(5));
}
rs.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//

FairCom Corporation
Copyright 2015 FairCom Corporation
30
c-treeSQL
JDBC Developer's Guide

// Update_CustomerMaster_Records()
//
// Update one record under locking control to demonstrate the effects
// of locking
//
private static void Update_CustomerMaster_Record()
{

System.out.println("\tUpdate record...");

try
{
stmt.executeUpdate("UPDATE custmast SET cm_custname = 'KEYON DOOLING' where cm_custnumb
= '1003'");

System.out.println("\tPress <ENTER> key to unlock");


System.in.read();

conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}
catch (Exception e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
31
Chapter 2
Quick Tour

Done

When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
private static void Done ()
{
System.out.println("DONE");

try
{
stmt.close();
// logout
System.out.println("\tLogout...");
conn.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
32
c-treeSQL
JDBC Developer's Guide

Additional Resources

We encourage you to explore the additional resources listed here:


 Complete source code for this tutorial can be found in JDBC_Tutorial3.java in your installation
directory, within the 'sdk\sql.jdbc\tutorials' directory for your platform.
Example for the Windows platform:
C:\FairCom\V10.x.x\win32\sdk\sql.jdbc\tutorials\JDBC_Tutorial3.java.
 Additional documentation may be found on the FairCom Web site at: www.faircom.com

www.faircom.com
All Rights Reserved
33
Chapter 2
Quick Tour

2.4 Transaction Processing


..\sdk\sql.jdbc\tutorials\JDBC_Tutorial4.java
Now we will discuss transaction processing as it relates to the c-treeACE SQL JDBC Interface.
Transaction processing provides a safe method by which multiple database operations spread across
separate tables/files are guaranteed to be atomic. By atomic, we mean that, within a transaction,
either all of the operations succeed or none of the operations succeed. This "either all or none"
atomicity insures that the integrity of the data in related tables/files is secure.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and You’re Done() !

Tutorial #4: Transaction Processing


Here we demonstrate transaction control.
 Initialize() - Connects to the c-treeACE Database Engine.
 Define() - Defines and creates our four tables/files.
 Manage() - Adds rows/records to multiple tables/files under transaction control.
 Done() - Disconnects from c-treeACE Database Engine.
Note our simple mainline:
import java.sql.*;
import java.io.*;

public class JDBC_Tutorial4 {


static Connection conn;
static Statement stmt;
//
// main()
//
// The main() function implements the concept of "init, define, manage
// and you're done..."
//
public static void main (String[] args)
throws java.io.IOException
{
Initialize();
Define();
Manage();
Done();

System.out.print("\nPress <ENTER> key to exit . . .");


System.in.read();
System.exit(0);
}
We suggest opening the source code with your own editor.

Continue now to review these four steps.

FairCom Corporation
Copyright 2015 FairCom Corporation
34
c-treeSQL
JDBC Developer's Guide

Init

First we need to open a connection to a database by providing the c-treeACE Database Engine with a
user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
private static void Initialize ()
{
System.out.println("INIT");

try
{
// load the driver
Class.forName ("ctree.jdbc.ctreeDriver");

// connect to server
System.out.println("\tLogon to server...");
conn = DriverManager.getConnection ("jdbc:ctree:6597@localhost:ctreeSQL", "ADMIN",
"ADMIN");

// disable commit after each single SQL statement


conn.setAutoCommit(false);

// create statement handles


stmt = conn.createStatement();
}
catch (SQLException e)
{
Handle_Exception(e);
}
catch (Exception e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
35
Chapter 2
Quick Tour

Define

The Define() step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the tables
//
private static void Define ()
{
System.out.println("DEFINE");

// delete tables ...


Delete_Tables();
// ...and re-create them with constraints
Create_CustomerMaster_Table();
Create_ItemMaster_Table();
Create_CustomerOrders_Table();
Create_OrderItems_Table();
try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Create_CustomerMaster_Table()
//
// Create the table CustomerMaster
//
private static void Create_CustomerMaster_Table ()
{
// define table CustomerMaster
System.out.println("\ttable CustomerMaster");

try
{
stmt.executeUpdate("CREATE TABLE custmast (" +
"cm_custnumb CHAR(4) PRIMARY KEY, " +
"cm_custzipc CHAR(9), " +
"cm_custstat CHAR(2), " +
"cm_custrtng CHAR(1), " +
"cm_custname VARCHAR(47), " +
"cm_custaddr VARCHAR(47), " +
"cm_custcity VARCHAR(47))"
);
}

FairCom Corporation
Copyright 2015 FairCom Corporation
36
c-treeSQL
JDBC Developer's Guide

catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Create_CustomerOrders_Table()
//
// Create the table CustomerOrders
//
private static void Create_CustomerOrders_Table ()
{
// define table CustomerOrders
System.out.println("\ttable CustomerOrders");

try
{
stmt.executeUpdate("CREATE TABLE custordr (" +
"co_ordrdate DATE, " +
"co_promdate DATE, " +
"co_ordrnumb CHAR(6) PRIMARY KEY, " +
"co_custnumb CHAR(4), " +
"FOREIGN KEY (co_custnumb) REFERENCES custmast)"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Create_OrderItems_Table()
//
// Create the table OrderItems
//
private static void Create_OrderItems_Table ()
{
// define table OrderItems
System.out.println("\ttable OrderItems");

try
{
stmt.executeUpdate("CREATE TABLE ordritem (" +
"oi_sequnumb SMALLINT, " +
"oi_quantity SMALLINT, " +
"oi_ordrnumb CHAR(6), " +
"oi_itemnumb CHAR(5), " +
"FOREIGN KEY (oi_itemnumb) REFERENCES itemmast, " +
"FOREIGN KEY (oi_ordrnumb) REFERENCES custordr)"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Create_ItemMaster_Table()
//
// Create the table ItemMaster
//
private static void Create_ItemMaster_Table ()
{
// define table ItemMaster

www.faircom.com
All Rights Reserved
37
Chapter 2
Quick Tour

System.out.println("\ttable ItemMaster");

try
{
stmt.executeUpdate("CREATE TABLE itemmast (" +
"im_itemwght INTEGER, " +
"im_itempric MONEY, " +
"im_itemnumb CHAR(5) PRIMARY KEY, " +
"im_itemdesc VARCHAR(47))"
);
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
38
c-treeSQL
JDBC Developer's Guide

Manage

The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// Populates table and perform a simple query
//
private static void Manage ()
{
System.out.println("MANAGE");

// populate the tables with data


Add_CustomerMaster_Records();
Add_ItemMaster_Records();

Add_Transactions();

// display the orders and their items


Display_CustomerOrders();
Display_OrderItems();
}

//
// Delete_Tables()
//
// This function removes all existing tables
//
private static void Delete_Tables ()
{

try
{
stmt.executeUpdate("DROP TABLE ordritem");
}
catch (SQLException e)
{
Handle_Exception(e);
}
try
{
stmt.executeUpdate("DROP TABLE custordr");
}
catch (SQLException e)
{
Handle_Exception(e);
}
try
{
stmt.executeUpdate("DROP TABLE custmast");
}
catch (SQLException e)
{

www.faircom.com
All Rights Reserved
39
Chapter 2
Quick Tour

Handle_Exception(e);
}
try
{
stmt.executeUpdate("DROP TABLE itemmast");
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_CustomerMaster_Records()
//
// This function adds records to table CustomerMaster from an
// array of strings
//
private static void Add_CustomerMaster_Records ()
{
String data[] = {
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
};

System.out.println("\tAdd records in table CustomerMaster...");

try
{
// add one record at time to table
for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO custmast VALUES " + data[i]);
}
}
catch (SQLException e)
{
Handle_Exception(e);
}
try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_ItemMaster_Records()
//
// This function adds records to table ItemMaster from an
// array of strings
//
private static void Add_ItemMaster_Records ()
{
String data[] = {
"(10,19.95,'1','Hammer')",
"(3, 9.99,'2','Wrench')",
"(4, 16.59,'3','Saw')",
"(1, 3.98,'4','Pliers')"
};

System.out.println("\tAdd records in table ItemMaster...");

try
{

FairCom Corporation
Copyright 2015 FairCom Corporation
40
c-treeSQL
JDBC Developer's Guide

// add one record at time to table


for (int i = 0; i < data.length; i++) {
stmt.executeUpdate("INSERT INTO itemmast VALUES " + data[i]);
}
}
catch (SQLException e)
{
Handle_Exception(e);
}
try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Add_Transactions()
//
// Add an Order and associated Items "as a transaction" to their
// respective tables. A transaction is committed or aborted if the
// customer number on the order is confirmed valid. Likewise each
// item in the order is verified to be a valid item.
//
private static void Add_Transactions()
{
int i, j = 0;
String[][] orders = {
{ "09/01/2002", "09/05/2002", "1", "1001" },
{ "09/02/2002", "09/06/2002", "2", "9999" }, // bad customer number
{ "09/22/2002", "09/26/2002", "3", "1003" }
};

String[][] items = {
{ "1", "1", "2", "1" },
{ "1", "2", "1", "2" },
{ "2", "1", "1", "3" },
{ "2", "2", "3", "4" },
{ "3", "1", "2", "3" },
{ "3", "2", "2", "99"} // bad item number
};

System.out.println("\tAdd transaction records...");

for (i = 0; i < orders.length; i++)


{
try
{
// add order record
stmt.executeUpdate("INSERT INTO custordr VALUES (" +
"'" + orders[i][0] + "'," +
"'" + orders[i][1] + "'," +
"'" + orders[i][2] + "'," +
"'" + orders[i][3] + "')");
}
catch (SQLException e)
{
Handle_Exception(e);
}

// process order items


while (items[j][0].compareTo(orders[i][2]) == 0)
{
try
{
// add item record
stmt.executeUpdate("INSERT INTO ordritem VALUES (" +

www.faircom.com
All Rights Reserved
41
Chapter 2
Quick Tour

items[j][1] + "," +
items[j][2] + "," +
"'" + items[j][0] + "'," +
"'" + items[j][3] + "')");
}
catch (SQLException e)
{
Handle_Exception(e);
}

// bump to next item


j++;

// exit the while loop on last item


if (j >= items.length)
break;
}

try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}
}

//
// Display_CustomerOrders()
//
// This function displays the contents of CustomerOrders table.
//
private static void Display_CustomerOrders ()
{
System.out.println("\n\tCustomerOrders Table...");

try
{
// execute a query statement
ResultSet rs = stmt.executeQuery ("SELECT * FROM custordr");

// fetch and display each individual record


while (rs.next()) {
System.out.println("\t " + rs.getString(3) + " " + rs.getString(4));
}
rs.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

//
// Display_OrderItems()
//
// This function displays the contents of OrderItems table.
//
private static void Display_OrderItems ()
{
System.out.println("\n\tOrderItems Table...");

try
{
// execute a query statement
ResultSet rs = stmt.executeQuery ("SELECT * FROM ordritem");

FairCom Corporation
Copyright 2015 FairCom Corporation
42
c-treeSQL
JDBC Developer's Guide

// fetch and display each individual record


while (rs.next()) {
System.out.println("\t " + rs.getString(3) + " " + rs.getString(4));
}
rs.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

www.faircom.com
All Rights Reserved
43
Chapter 2
Quick Tour

Done

When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
private static void Done ()
{
System.out.println("DONE");

Delete_Tables();
try
{
conn.commit();
}
catch (SQLException e)
{
Handle_Exception(e);
}

try
{
stmt.close();
// logout
System.out.println("\tLogout...");
conn.close();
}
catch (SQLException e)
{
Handle_Exception(e);
}
}

FairCom Corporation
Copyright 2015 FairCom Corporation
44
c-treeSQL
JDBC Developer's Guide

Additional Resources

We encourage you to explore the additional resources listed here:


 Complete source code for this tutorial can be found in JDBC_Tutorial4.java in your installation
directory, within the 'sdk\sql.jdbc\tutorials' directory for your platform.
Example for the Windows platform:
C:\FairCom\V10.x.x\win32\sdk\sql.jdbc\tutorials\JDBC_Tutorial4.java.
 Additional documentation may be found on the FairCom Web site at: www.faircom.com

www.faircom.com
All Rights Reserved
45
Chapter 3

Basic JDBC Driver Operations

3.1 Introduction
This chapter describes how to set up and get started using the c-treeACE SQL JDBC Driver.

3.2 Required Java Environment


You must have a supported Java development or runtime environment on each system that uses the
c-treeACE SQL JDBC Driver. The c-treeACE SQL JDBC Driver requires the following development
(or compatible runtime) environments:
 Java JDK™ Version 1.6 or higher
(See Java Requirements for c-treeACE SQL /doc/knowledgebase/55631.htm for the JDK version
required for your c-treeACE SQL environment,)
You must have one of these environments or their associated Java runtime environments to use the
JDBC Driver. For details on obtaining this software, visit Click here to download
http://www.oracle.com/technetwork/java/javase/downloads/index.html.

3.3 Setting Up the JDBC Driver: Web Server


In a Web server environment, the c-treeACE SQL JDBC driver and Java applets that use it reside on
a host system. No additional driver software is required on the client machine. Client applications
must support a Java virtual machine compatible with the Java JDK Version 1.6 or later.
Client applications invoke a JDBC applet through a Web page on the server. The browser downloads
both the applet and the JDBC Driver from the server (usually in compressed format) and runs the
applet. The Java applet opens a database connection (see "Connecting to a Database" (page 49))
and accesses the database using the JDBC API.
A general JDBC security restriction is that applets can only open a database connection from the
server from which they are downloaded. That means the host system must be running both the HTTP
Web server and the c-treeACE SQL Server process.
To set up the JDBC Driver for an applet on a Web server, complete these steps:
 Copy compiled class files for the c-treeACE SQL JDBC Driver and the applet to a directory
accessible to the Web page that will invoke the applet.
 Compress all the class files into a single Java Archive (JAR) file.
 Create the Web page that will invoke the applet.
The following sections describe these steps.

www.faircom.com
All Rights Reserved
47
Chapter 3
Basic JDBC Driver Operations

Copying JDBC Driver and Applet Class Files


On both Windows and Unix, the class files for the JDBC Driver are created in the
classes\ctreeJDBC.jar file. Copy the jar files from that directory to a directory accessible to the Web
page. Do the same for the applet’s class file.
For example:
systpe@mydomain% cd $webroot
/vol6/webroot
systpe@mydomain% mkdir test
systpe@mydomain% cd test
/vol6/webroot/test
systpe@isis% cp -i $TPEROOT/classes/ctreeJDBC.jar
systpe@isis% cp -i /applet_test/ctreeJDBCApplet.class

Creating a Web Page That Invokes the Applet


At a minimum, the page must include the APPLET tag that invokes the applet.
For example, the following page includes little else but the APPLET tag. The example’s APPLET tag
specifies the c-treeJDBCApplet.class and ctreeJDBCTest.jar files from the preceding sections, as
well as class-name and connection parameters to pass to the applet.

<html>
<head>
<title>Test</title>
</head>
<body>
<p>
Here, in all its glory, is the ctreeJDBCApplet test applet!
<center>
<applet code="c-treeJDBCApplet.class"
archive="c-treeJDBCTest.jar" width=500 height=400>
<param name=Driver value="ctree.jdbc.ctreeDriver">
<param name=URL value="jdbc:ctree:6597@mydomain:ctreeSQL">
<param name=User value="ADMIN">
<param name=Password value="dummy">
</applet>
</center>
</body>
</html>

3.4 Setting Up the JDBC Driver: Application Server


In an application server environment, the system on which the JDBC application runs also has the
JDBC driver installed. This configuration provides good performance when users are on the same
system or can execute the JDBC application across a network.
To set up the JDBC Driver, you must have access to a system (Unix or Windows) where the
c-treeACE SQL libraries and executable files have been built. On both Windows and Unix, the JDBC
class files are created in the classes\ctreeJDBC.jar file.
If the application server is a different system than the system used for those c-treeACE SQL libraries
and executables, you may need to copy the jar file to the application server. Then, you need to set
the CLASSPATH environment variable to include the directory where the class files reside.
The following sections describe these steps.

FairCom Corporation
Copyright 2015 FairCom Corporation
48
c-treeSQL
JDBC Developer's Guide

Copying JDBC Driver Files to the Application Server (If Necessary)


This step is not necessary if the application server has access to the disk containing the class files
(through a Windows network or NFS-mounted disks on Unix).
Otherwise, you must first copy files to the application server. On Unix and Windows systems, use any
available utility to copy the jar files to the application server.

Setting Environment Variables


Whether the JDBC Driver class files reside locally or on network-served disks, you must set the
CLASSPATH environment variable to point to the class files.
On both Windows and Unix the CLASSPATH environment variable must point to the jar file
ctreeJDBC.jar.
With Windows, you can set the CLASSPATH environment variable at the Windows command prompt,
as in the following example:
set CLASSPATH=%CLASSPATH%;
.;
c:\<jdk_version>\jre\lib\rt.jar;
c:\FairCom\V10.0.0\win32\lib\sql.jdbc\ctreeJDBC.jar
(For environment variables to persist across different processes, set them using the Windows Control
Panel’s System utility, and set them as system variables.)
Also, make sure the PATH environment variable includes the appropriate Java compiler directory.
Example syntax could be as follows:
PATH=%PATH%;
c:\<jdk_version>\bin;
c:\<jdk_version>\jre\bin\classic
(Again, for the environment variables to persist across different processes, set them using the
Windows Control Panel’s System utility, and set them as system variables.)

Running the Sample Application


The <c-treeACE SQL distribution includes a test Java application, ctreeTest.class, that exercises the
JDBC interfaces implemented by the JDBC Driver. The application connects to the specified
database (or creates a default connection hard coded in the application) and presents a limited
interactive c-treeACE SQL interface.
You can run the sample application to check the setup of the JDBC Driver in an application server
environment.
For example, on Windows (using the Java JDK), the following command line supplies a connection
URL to run the sample program (see "Connecting to a Database" (page 49) for details on specifying a
URL):
C:\>java ctreeTest jdbc:ctree:6597@localhost:ctreeSQL
If you have a Java compiler, you can copy the sample program source code and modify it. The
source file is src\jdbc\ctreeTest.java on the system where the class files were built.

3.5 Connecting to a Database


JDBC applications must perform two steps to connect to a database:
1. Load the JDBC driver
2. Connect to the driver

www.faircom.com
All Rights Reserved
49
Chapter 3
Basic JDBC Driver Operations

Load the JDBC Driver Using Class.forName


The Class.forName() method takes as its argument the fully-qualified class name for the c-treeACE
SQL JDBC Driver. If it finds the class, the method loads and links the class, and returns the Class
object representing the class.
The fully-qualified class name for the c-treeACE SQL JDBC Driver is ctree.jdbc.ctreeDriver. To load
the JDBC Driver, use it as the argument to the Class.forName() method:
// Load the driver
Class.forName ("ctree.jdbc.ctreeDriver");

Connect to the JDBC Driver Using DriverManager.GetConnection


To connect to a c-treeACE SQL database through the c-treeACE SQL JDBC Driver, an application
specifies:
 A database connection string in the form of a JDBC URL
 User authentication detail (user name and password)
Applications specify this information as arguments to the DriverManager.GetConnection() method.

Java URL Connection String


DriverManager.GetConnection() requires at least one argument, a character string specifying a
database connection URL. For the c-treeACE SQL JDBC Driver, the URL takes the following form:
jdbc:ctree:port@host_name:db_name
The URL string has the following components:
jdbc:ctree An identifying protocol and subprotocol string for the c-treeACE SQL JDBC Driver.

:port The port number associated with the c-treeACE SQL server on the host system.

@host_name Name of the server system where the database resides.


:db_name Name of the database.

For example, the default URL in the sample application is jdbc:ctree:6597@localhost:ctreeSQL.


When passed to DriverManager.GetConnection(), this URL specifies that the c-treeACE SQL JDBC
Driver be used to connect to the database ctreeSQL on the server named locahost.

User Authentication Detail


DriverManager.GetConnection() accepts three variants of user authentication detail:
 User name and password passed as two character string arguments:
Connection con = DriverManager.getConnection (url, "ADMIN" "ADMIN" );
 User name and password passed as a single Properties object:
Connection con = DriverManager.getConnection (url, prop );
Note that the c-treeACE SQL JDBC Driver expects the keys of the Properties object to be named
user and password when it processes the object. Application code must use those names when it
populates the Properties object:
prop.put("user", userid);
prop.put("password", passwd);
 User name and password omitted. The c-treeACE SQL JDBC Driver connects to the database
with a blank username and null password:
Connection con = DriverManager.getConnection (url);

FairCom Corporation
Copyright 2015 FairCom Corporation
50
c-treeSQL
JDBC Developer's Guide

An Example Connection
The following example shows a code excerpt that illustrates loading the driver and connecting to the
default server and database. The following example uses the form of
DriverManager.GetConnection() that takes authentication information as a single Properties object.

Example Loading the JDBC Driver and Connecting to a Database


String url = "jdbc:ctree:6597@localhost:ctreeSQL";
String userid = "ADMIN";
String passwd = "ADMIN";

// Load the driver


Class.forName ("ctree.jdbc.ctreeDriver");

// Attempt to connect to a driver. Each one


// of the registered drivers will be loaded until
// one is found that can process this URL.
java.util.Properties prop = new java.util.Properties();
prop.put("user", userid);
prop.put("password", passwd);

Connection con = DriverManager.getConnection (url, prop);

Connection Pooling Support in JDBC


The IBM’s Websphere 4.0 Application server uses the JDBC APIs DataSource, PooledConnection
and ConnectionPoolDataSource to connect to any data source. These APIs are part of the javax.sql
package. It is mandatory to support them when working with IBM's Websphere 4.0 middleware.

javax.sql Package
The c-treeACE SQL JDBC javax.sql package provides the APIs for server side data source access
and processing. This is included in the Java 2 SDK version 1.6, Standard Edition.
The javax.sql package provides the following:
 The DataSource interface as an alternative to the DriverManager for establishing a connection
with a data source
 Connection pooling

Using A DataSource Object To Make A Connection


The <c-treeACE SQL JDBC javax.sql package provides the preferred way to make a connection with
a data source. The DriverManager class, the original mechanism, is still valid, and code using it will
continue to run. However, the newer DataSource mechanism is preferred because it offers many
advantages over the DriverManager mechanism.
The following are the main advantages of using a DataSource object to make a connection:
 Applications do not need to hard code a driver class.
 Changes can be made to a data source’s properties, which means that it is not necessary to
make changes in application code when something about the data source or driver changes.
 Connection pooling and distributed transactions are available through a DataSource object that is
implemented to work with the middle-tier infrastructure. Connections made through the
DriverManager do not have connection pooling or distributed transaction capabilities.

www.faircom.com
All Rights Reserved
51
Chapter 3
Basic JDBC Driver Operations

A particular DataSource object represents a particular physical data source, and each connection the
DataSource object creates is a connection to that physical data source. A DataSource object can be
implemented to work with the middle tier infrastructure so that the connections it produces will be
pooled for reuse. An application that uses such a DataSource implementation will automatically get a
connection that participates in connection pooling. A DataSource object can also be implemented to
work with the middle tier infrastructure so that the connections it produces can be used for distributed
transactions without any special coding.

Connection Pooling
Connections made via a DataSource object that is implemented to work with a middle tier connection
pool manager will participate in connection pooling. This can improve performance dramatically
because creating new connections is very expensive. Connection pooling allows a connection to be
used and reused, thus reducing the number of new connections that need to be created.
Connection pooling is totally transparent. It is done automatically in the middle tier of a J2EE
Environment, and hence from an application’s viewpoint, no change in code is required. An
application simply uses the DataSource.getConnection() method to get the pooled connection and
uses it the same way it uses any Connection object.

Implementation in c-treeACE SQL JDBC Driver


To support working with IBM's Websphere 4.0 Application server, the following interfaces from the
package javax.sql have been implemented.
 javax.sql.DataSource
This is a factory for connections to the physical data source that this DataSource object represents.
An object that implements the DataSource interface will typically be registered with a naming service
based on the Java Naming and Directory (JNDI) API.
 javax.sql.PooledConnection interfaces
An object that provides hooks for connection pool management. A PooledConnection object
represents a physical connection to a data source. The connection can be recycled rather than being
closed when an application is finished with it, thus reducing the number of connections that need to
be made.
 javax.sql.ConnectionPoolDataSource
This is a factory for PooledConnection objects. An object that implements this interface will typically
be registered with a naming service that is based on the Java Naming and Directory Interface (JNDI).

3.6 Managing Transactions Explicitly to Improve Performance


By default, new connections in c-treeACE SQL JDBC applications are in autocommit mode.
In autocommit mode every c-treeACE SQL statement executes in its own transaction:
 After successful completion, the JDBC Driver automatically commits the transaction.
 If the statement execution fails, the JDBC Driver automatically rolls back the transaction.

Note: In autocommit mode, the JDBC Driver does not issue a commit after SELECT and CALL
statements. The driver assumes these statements generate result sets and relies on the application
to explicitly commit or roll back the transaction after it processes any result set and closes the
statement.

You can change transaction mode to manual commit by calling the Connection.setAutoCommit()
method. In manual commit mode, applications must commit a transaction by using the

FairCom Corporation
Copyright 2015 FairCom Corporation
52
c-treeSQL
JDBC Developer's Guide

Connection.commit() method. Similarly, applications must explicitly roll back a transaction by


invoking the Connection.rollback() method.
You will improve the performance of your programs by setting autocommit to false after creating a
Connection object with the Connection.setAutoCommit() method:
Connection con = DriverManager.getConnection ( url, prop);
.
.
.
con.setAutoCommit(false);

3.7 Query Timeout Options


The c-treeACE SQL supports a timeout option for an executing query. This feature can ensure that an
unintended query statement does not consume excessive processing time.
With the c-treeACE SQL JDBC Driver, use the setQueryTimeout() method of the java.sql.Statement
interface as shown here.

c-treeSQL JDBC Example


Class.forName (“ctree.jdbc.ctreeDriver”);
Connection myConnection = DriverManager.getConnection(“jdbc:ctree:6597@localhost:ctreeSQL”,
ADMIN, ADMIN”);
Statement myStatement = myConnection.createStatement();

String query = “SELECT TOP 50000 FROM my_big_table WHERE this < that AND this_string = 'that_string'
ORDER BY foo”
myStatement:setQueryTimeout(5);
myStatement.executeUpdate(query);

3.8 Driver Socket SEND/RECV Timeout


A send/recv timeout option has been added such that a c-treeACE SQL JDBC client can request a
timeout for a socket. If the client experiences a lengthy wait for the server to reply, the client can
continue to work after closing the connection.
With the c-treeACE SQL JDBC Driver, it is possible at connection time to set a timeout value in
milliseconds using the DriverManager.getConnection(string, properties) method as follows.

Example
Properties info = new Properties();

info.setProperty("user","ADMIN");
info.setProperty("password","ADMIN");
info.setProperty("sock_timeout","30000");
conn = DriverManager.getConnection ("jdbc:ctree:6597@localhost:ctreeSQL", info);

Note: The time-out is an integer it is specified as a string.

3.9 JDBC Version Information


Version information is available from the c-treeACE SQL JDBC driver. The Java JDBC
getDriverMajorVersion() and getDriverMinorVersio() methods can be used to retrieve these
values.

www.faircom.com
All Rights Reserved
53
Chapter 3
Basic JDBC Driver Operations

JDBC Version Example


Connection con = DriverManager.getConnection ( url, prop);
// Get the DatabaseMetaData object and display
// some information about the connection
DatabaseMetaData dma = con.getMetaData ();

o.println("\nConnected to " + dma.getURL());


o.println("Driver " +
dma.getDriverName());
o.println("Version " +
dma.getDriverVersion());

FairCom Corporation
Copyright 2015 FairCom Corporation
54
Chapter 4

JDBC Conformance Notes

4.1 Supported Data Types


The c-treeACE SQL JDBC Driver supports standard JDBC mapping of JDBC types to corresponding
Java types.
In the JDBC methods CallableStatement.get..XXX() and PreparedStatement.set...XXX() methods,
XXX is a Java type:
 For ...setXXX() methods, the driver converts the Java type to the c-treeACE SQL JDBC type
shown in the following table before sending it to the database.
 For ...getXXX() methods, the driver converts the c-treeACE SQL JDBC type returned by the
database to the Java type shown in “Mapping Between JDBC and Java Data Types” before
returning it to the ...getXXX() method.
Mapping Between Java and JDBC Data Types

Java Type JDBC type Java Type JDBC type

String VARCHAR or float REAL


LONGVARCHAR

java.math.BigDecimal NUMERIC double DOUBLE

boolean BIT byte[] VARBINARY or


LONGVARBINARY

byte TINYINT java.sql.Date DATE

short SMALLINT java.sql.Time TIME

int INTEGER java.sql.Timestamp TIMESTAMP


long BIGINT

Mapping Between JDBC and Java Data Types

JDBC type Java type JDBC type Java type

CHAR String REAL float

VARCHAR String FLOAT double

LONGVARCHAR String DOUBLE double

NUMERIC java.math.BigDecimal BINARY byte[]

www.faircom.com
All Rights Reserved
55
Chapter 4
JDBC Conformance Notes

JDBC type Java type JDBC type Java type

DECIMAL java.math.BigDecimal VARBINARY byte[]


BIT boolean LONGVARBINARY byte[]
TINYINT byte DATE java.sql.Date
SMALLINT short TIME java.sql.Time
INTEGER int TIMESTAMP java.sql.Timestamp
BIGINT long

4.2 Return Values for DatabaseMetaData Methods


Applications call methods of the DatabaseMetaData class to retrieve details about the JDBC support
provided by a specific driver.
The following table lists each method of the DatabaseMetaData class and shows what the c-treeACE
SQL JDBC Driver returns when an applications calls the method. For details on the format and usage
of each method, see the Java Platform Core API documentation.
The following example shows an excerpt from the sample program that illustrates calling methods of
DatabaseMetaData.

Getting Driver Information Through DatabaseMetaData Methods


Connection con = DriverManager.getConnection ( url, prop);
.
.
.
// Get the DatabaseMetaData object and display
// some information about the connection

DatabaseMetaData dma = con.getMetaData ();

o.println("\nConnected to " + dma.getURL());


o.println("Driver " + dma.getDriverName());
o.println("Version " + dma.getDriverVersion());

Many of the methods return lists of information as an object of type ResultSet. Use the normal
ResultSet methods such as getString() and getInt() to retrieve the data from the result sets.
Return Values for DatabaseMetaData Methods

Method Description Returns


allProceduresAreCallable() Can all the procedures returned by getProcedures True
be called by the current user?
allTablesAreSelectable() Can all the tables returned by getTable be False
SELECTed by the current user?
dataDefinitionCausesTransactionC Does a data definition statement within a transaction False
ommit() force the transaction to commit?

dataDefinitionIgnoredInTransaction Is a data definition statement within a transaction False


s () ignored?

FairCom Corporation
Copyright 2015 FairCom Corporation
56
c-treeSQL
JDBC Developer's Guide

Method Description Returns


doesMaxRowSizeIncludeBlobs() Did getMaxRowSize() include LONGVARCHAR and False
LONGVARBINARY blobs?

getBestRowIdentifier(String, String, Get a description of a table’s optimal set of columns (result set)
String, int, boolean) that uniquely identifies a row.

getCatalogs() Get the catalog names available in this database. "Driver not capable"

getCatalogSeparator() What’s the separator between catalog and table “” (blank)


name?
getCatalogTerm() What’s the database vendor’s preferred term for “” (blank)
“catalog”?

getColumnPrivileges(String, String, Get a description of the access rights for a table’s (result set)
String, String) columns.

getColumns(String, String, String, Get a description of table columns available in a (result set)
String) catalog.

getCrossReference(String, String, Get a description of the foreign key columns in the (result set)
String, String, String, String) foreign key table that reference the primary key
columns of the primary key table (describe how one
table imports another’s key.) This should normally
return a single foreign key/primary key pair (most
tables only import a foreign key from a table once.)
They are ordered by FKTABLE_CAT,
FKTABLE_SCHEM, FKTABLE_NAME, and
KEY_SEQ.

getDatabaseProductName() What’s the name of this database product? “c-treeSQL”

getDatabaseProductVersion() What’s the version of this database product? “11.04.0000”

getDefaultTransactionIsolation() What’s the database’s default transaction isolation TRANSACTION_SERI


level? The values are defined in ALIZABLE
java.sql.Connection.

getDriverMajorVersion() What’s this JDBC driver’s major version number? 11

getDriverMinorVersion() What’s this JDBC driver's minor version number? 4


getDriverName() What’s the name of this JDBC driver? “ctree.jdbc.ctreeDriver”

getDriverVersion() What’s the version of this JDBC driver? “11.04.0000”

getExportedKeys(String, String, Get a description of the foreign key columns that (result set)
String) reference a table’s primary key columns (the foreign
keys exported by a table).
getExtraNameCharacters() Get all the “extra” characters that can be used in null
unquoted identifier names (those beyond a-z, A-Z,
0-9 and _).

getIdentifierQuoteString () What’s the string used to quote SQL identifiers? “"”


This returns a space “ ” if identifier quoting isn’t
supported.

getImportedKeys(String, String, Get a description of the primary key columns that (result set)
String) are referenced by a table’s foreign key columns (the
primary keys imported by a table).

www.faircom.com
All Rights Reserved
57
Chapter 4
JDBC Conformance Notes

Method Description Returns


getIndexInfo(String, String, String, Get a description of a table’s indices and statistics. (result set)
boolean, boolean)
getMaxBinaryLiteralLength() How many hex characters can you have in an inline 32000
binary literal?
getMaxCatalogNameLength() What’s the maximum length of a catalog name? 32

getMaxCharLiteralLength() What’s the max length for a character literal? 2000

getMaxColumnNameLength() What’s the limit on column name length? 32

getMaxColumnsInGroupBy() What’s the maximum number of columns in a 0 (no limit)


“GROUP BY” clause?

getMaxColumnsInIndex() What’s the maximum number of columns allowed in 100


an index?
getMaxColumnsInOrderBy() What’s the maximum number of columns in an 0 (no limit)
“ORDER BY” clause?
getMaxColumnsInSelect() What’s the maximum number of columns in a 0 (no limit)
“SELECT” list?

getMaxColumnsInTable() What’s the maximum number of columns in a table? 500

getMaxConnections() How many active connections can we have at a time 10


to this database?

getMaxCursorNameLength() What’s the maximum cursor name length? 32

getMaxIndexLength() What’s the maximum length of an index (in bytes)? 0 (no limit)

getMaxProcedureNameLength() What’s the maximum length of a procedure name? 32

getMaxRowSize() What’s the maximum length of a single row? 0 (no limit)


getMaxSchemaNameLength() What’s the maximum length allowed for a schema 32
name?
getMaxStatementLength() What’s the maximum length of a SQL statement? 32MB (35000 prior to
V10.3)
getMaxStatements() How many active statements can we have open at 0 (no limit)
one time to this database?

getMaxTableNameLength() What’s the maximum length of a table name? 32

getMaxTablesInSelect() What’s the maximum number of tables in a 250


SELECT?

getMaxUserNameLength() What’s the maximum length of a user name? 32

FairCom Corporation
Copyright 2015 FairCom Corporation
58
c-treeSQL
JDBC Developer's Guide

Method Description Returns


getNumericFunctions() Get a comma separated list of math functions. ABS, ACOS,
ASIN, ATAN,
ATAN2, CEILING,
COS, COT,
DATALENGTH,
DEGREES,
EXP, FLOOR,
ISNUMERIC,
LOG, LOG10,
MOD, PI,
POWER,
RADIANS,
RAND,
ROUND,
SIGN, SIN,
SQRT, TAN,
TRUNCATE
getPrimaryKeys(String, String, Get a description of a table’s primary key columns. (result set)
String)
getProcedureColumns(String, Get a description of a catalog’s stored procedure (result set)
String, String, String) parameters and result columns.

getProcedures(String, String, Get a description of stored procedures available in a (result set)


String) catalog.
getProcedureTerm() What’s the database vendor’s preferred term for “procedure”
“procedure”?
getSchemas() Get the schema names available in this database. (result set)

getSchemaTerm() What’s the database vendor’s preferred term for “Owner”


“schema”?

getSearchStringEscape() This is the string that can be used to escape ‘_’ or “\”
‘%’ in the string pattern style catalog search
parameters.

getSQLKeywords() Get a comma separated list of all a database’s SQL null


keywords that are NOT also SQL92 keywords.

getStringFunctions() Get a comma separated list of string functions. ASCII, LTRIM, CHAR,
DIFFERENCE,
INSERT, LCASE,
LEFT, REPEAT,
REPLACE,
SOUNDEX, SPACE,
SUBSTRING, UCASE,
RTRIM, CONCAT,
LENGTH, LOCATE,
TRIM

www.faircom.com
All Rights Reserved
59
Chapter 4
JDBC Conformance Notes

Method Description Returns


getSystemFunctions() Get a comma separated list of system functions. SQL_FN_SYS_USER
NAME,
SQL_FN_SYS_IFNUL
L,
SQL_FN_SYS_DBNA
ME
getTablePrivileges(String, String, Get a description of the access rights for each table (result set)
String) available in a catalog.

getTables(String, String, String, Get a description of tables available in a catalog. (result set)
String [])

getTableTypes() Get the table types available in this database. SYNONYM, SYSTEM
TABLE, TABLE, VIEW

getTimeDateFunctions() Get a comma separated list of time and date CURRENT_DATE,


functions.
CURRENT_TIME,
CURRENT_TIMESTA
MP,
CURDATE,
CURTIME,
DATEADD,
DATEDIFF,
DAYNAME,
DAYOFMONTH,
DAYOFWEEK,
DAYOFYEAR,
EXTRACT,
HOUR,
MINUTE,
MONTH,
MONTHNAME,
NOW,
QUARTER,
SECOND,
SYSDATE,
SYSTIME,
SYSTIMESTAMP,
TIMESTAMPADD,
TIMESTAMPDIFF,
WEEK,
getTypeInfo() Get a description of all the standard SQL types (result set)
supported by this database.

FairCom Corporation
Copyright 2015 FairCom Corporation
60
c-treeSQL
JDBC Developer's Guide

Method Description Returns


getURL() What’s the url for this database? (the URL)

getUserName() What’s our user name as known to the database? (the userid)

getVersionColumns(String, String, Get a description of a table’s columns that are (result set)
String) automatically updated when any value in a row is
updated.
isCatalogAtStart() Does a catalog appear at the start of a qualified True
table name? (Otherwise it appears at the end)
isReadOnly() Is the database in read-only mode? False

nullPlusNonNullIsNull() Are concatenations between NULL and non-NULL True


values NULL? A JDBC-Compliant driver always
returns true.

nullsAreSortedAtEnd() Are NULL values sorted at the end regardless of False


sort order?
nullsAreSortedAtStart() Are NULL values sorted at the start regardless of False
sort order?

nullsAreSortedHigh() Are NULL values sorted high? False

nullsAreSortedLow() Are NULL values sorted low? True


storesLowerCaseIdentifiers() Does the database treat mixed case unquoted SQL True or False
identifiers as case insensitive and store them in
lower case? Depends on the
identifier case
specified during the
creation of database.
storesLowerCaseQuotedIdentifiers( Does the database treat mixed case quoted SQL True or False
) identifiers as case insensitive and store them in
lower case? Depends on the
identifier case
specified during the
creation of database.
storesMixedCaseIdentifiers() Does the database treat mixed case unquoted SQL False
identifiers as case insensitive and store them in
mixed case?

storesMixedCaseQuotedIdentifiers( Does the database treat mixed case quoted SQL False
) identifiers as case insensitive and store them in
mixed case?
storesUpperCaseIdentifiers() Does the database treat mixed case unquoted SQL True or False
identifiers as case insensitive and store them in
upper case? Depends on the
identifier case
specified during the
creation of database.
storesUpperCaseQuotedIdentifiers( Does the database treat mixed case quoted SQL False
) identifiers as case insensitive and store them in
upper case?

supportsAlterTableWithAddColumn Is “ALTER TABLE” with add column supported? True


()

www.faircom.com
All Rights Reserved
61
Chapter 4
JDBC Conformance Notes

Method Description Returns


supportsAlterTableWithDropColum Is “ALTER TABLE” with drop column supported? True
n()

supportsANSI92EntryLevelSQL() Is the ANSI92 entry level SQL grammar supported? True


All JDBC-Compliant drivers must return true.
supportsANSI92FullSQL() Is the ANSI92 full SQL grammar supported? False

supportsANSI92IntermediateSQL() Is the ANSI92 intermediate SQL grammar False


supported?

supportsCatalogsInDataManipulati Can a catalog name be used in a data manipulation False


on() statement?
supportsCatalogsInIndexDefinitions Can a catalog name be used in an index definition False
() statement?
supportsCatalogsInPrivilegeDefiniti Can a catalog name be used in a privilege definition False
ons() statement?
supportsCatalogsInProcedureCalls( Can a catalog name be used in a procedure call False
) statement?
supportsCatalogsInTableDefinitions Can a catalog name be used in a table definition False
() statement?

supportsColumnAliasing() Is column aliasing supported? If so, the SQL AS True


clause can be used to provide names for computed
columns or to provide alias names for columns as
required.
supportsConvert() Is the CONVERT function between SQL types True
supported?
supportsConvert(int, int) Is CONVERT between the given SQL types True or False
supported?
Depends on the types
being converted
supportsCoreSQLGrammar() Is the ODBC Core SQL grammar supported? True

supportsCorrelatedSubqueries() Are correlated subqueries supported? A True


JDBC-Compliant driver always returns true.

supportsDataDefinitionAndDataMa Are both data definition and data manipulation True


nipulationTransactions () statements within a transaction supported?

supportsDataManipulationTransacti Are only data manipulation statements within a False


onsOnly() transaction supported?

supportsDifferentTableCorrelationN If table correlation names are supported, are they False


ames() restricted to be different from the names of the
tables?
supportsExpressionsInOrderBy() Are expressions in “ORDER BY” lists supported? True

supportsExtendedSQLGrammar() Is the ODBC Extended SQL grammar supported? True

supportsFullOuterJoins() Are full nested outer joins supported? False

FairCom Corporation
Copyright 2015 FairCom Corporation
62
c-treeSQL
JDBC Developer's Guide

Method Description Returns


supportsGroupBy() Is some form of “GROUP BY” clause supported? True

supportsGroupByBeyondSelect() Can a “GROUP BY” clause add columns not in the True
SELECT provided it specifies all the columns in the
SELECT?

supportsGroupByUnrelated() Can a “GROUP BY” clause use columns not in the False
SELECT?

supportsIntegrityEnhancementFacil Is the SQL Integrity Enhancement Facility True


ity() supported?

supportsLikeEscapeClause() Is the escape character in “LIKE” clauses True


supported? A JDBC-Compliant driver always returns
true.

supportsLimitedOuterJoins() Is there limited support for outer joins? (This will be True
true if supportFullOuterJoins is true.)

supportsMinimumSQLGrammar() Is the ODBC Minimum SQL grammar supported? All True


JDBC-Compliant drivers must return true.
supportsMixedCaseIdentifiers() Does the database treat mixed case unquoted SQL False
identifiers as case sensitive and as a result store
them in mixed case? A JDBC-Compliant driver will
always return false.
supportsMixedCaseQuotedIdentifie Does the database treat mixed case quoted SQL True
rs() identifiers as case sensitive and as a result store
them in mixed case? A JDBC-Compliant driver will
always return true.

supportsMultipleResultSets() Are multiple ResultSets from a single execute False


supported?

supportsMultipleTransactions () Can we have multiple transactions open at once (on True


different connections)?

supportsNonNullableColumns() Can columns be defined as non-nullable? A True


JDBC-Compliant driver always returns true.

supportsOpenCursorsAcrossComm Can cursors remain open across commits? False


it()

supportsOpenCursorsAcrossRollba Can cursors remain open across rollbacks? False


ck()

supportsOpenStatementsAcrossCo Can statements remain open across commits? True


mmit()
supportsOpenStatementsAcrossRo Can statements remain open across rollbacks? True
llback()

supportsOrderByUnrelated() Can an “ORDER BY” clause use columns not in the True
SELECT?

supportsOuterJoins() Is some form of outer join supported? True

supportsPositionedDelete() Is positioned DELETE supported? True

www.faircom.com
All Rights Reserved
63
Chapter 4
JDBC Conformance Notes

Method Description Returns


supportsPositionedUpdate() Is positioned UPDATE supported? True
supportsSchemasInDataManipulati Can a schema name be used in a data manipulation True
on() statement?

supportsSchemasInIndexDefinition Can a schema name be used in an index definition True


s() statement?
supportsSchemasInPrivilegeDefiniti Can a schema name be used in a privilege definition True
ons() statement?

supportsSchemasInProcedureCalls Can a schema name be used in a procedure call True


() statement?

supportsSchemasInTableDefinition Can a schema name be used in a table definition True


s() statement?
supportsSelectForUpdate() Is SELECT for UPDATE supported? True

supportsStoredProcedures() Are stored procedure calls using the stored True


procedure escape syntax supported?

supportsSubqueriesInComparisons Are subqueries in comparison expressions True


() supported? A JDBC-Compliant driver always returns
true.

supportsSubqueriesInExists() Are subqueries in ‘exists’ expressions supported? A True


JDBC-Compliant driver always returns true.

supportsSubqueriesInIns() Are subqueries in ‘in’ statements supported? A True


JDBC-Compliant driver always returns true.

supportsSubqueriesInQuantifieds() Are subqueries in quantified expressions supported? True


A JDBC-Compliant driver always returns true.

supportsTableCorrelationNames() Are table correlation names supported? A True


JDBC-Compliant driver always returns true.

supportsTransactionIsolationLevel(i Does the database support the given transaction True


nt) isolation level?

supportsTransactions () Are transactions supported? If not, commit is a True


no-op and the isolation level is
TRANSACTION_NONE.
supportsUnion() Is SQL UNION supported? True

supportsUnionAll() Is SQL UNION ALL supported? True


usesLocalFilePerTable() Does the database use a file for each table? False

usesLocalFiles() Does the database store tables in a local file? False

JDBC 2.0

deletesAreDetected(int) Indicates whether or not a visible row delete can be False


detected by calling ResultSet.rowDeleted().

FairCom Corporation
Copyright 2015 FairCom Corporation
64
c-treeSQL
JDBC Developer's Guide

getConnection() Retrieves the connection that produced this The connection that
metadata object. produced this
metadata object

getUDTs(String, String, String, int[]) Gets a description of the userdefined types defined Empty ResultSet
in a particular schema. object

insertsAreDetected(int) Indicates whether or not a visible row insert can be False


detected by calling ResultSet.rowInserted().

othersDeletesAreVisible(int) Indicates whether deletes made by others are False


visible.
othersUpdatesAreVisible(int) Indicates whether updates made by others are False
visible.
ownDeletesAreVisible(int) Indicates whether a result set’s own deletes are False
visible.
ownInsertsAreVisible(int) Indicates whether inserts made by others are visible. False
ownUpdatesAreVisible(int) Indicates whether a result set’s own updates are False
visible.
supportsBatchUpdates() Indicates whether the driver supports batch updates. True

supportsResultSetType(int) Does the database support the given result set True if result set type
type? is
FORWARD_ONLY
supportsResultSetConcurrency(int, Does the database support the concurrency type in True if result set type
int) combination with the given result set type? is FORWARD_ONLY
and if concurrency
type is
CONCUR_READ_ON
LY
updatesAreDetected(int) Indicates whether or not a visible row update can be False
detected by calling the method
ResultSet.rowUpdated.

JDBC 3.0

supportsSavepoints() Does the database support savepoints False

supportsNamedParameters() Does the database support named parameters to False


callable statements

supportsMultipleOpenResults() Indicates whether it is possible to have multiple False


ResultSet objects returned from a Callable
Statement object simultaneously

supportsGetGeneratedKeys() Indicates whether auto-generated keys can be False


retrieved after a statement has been executed

getSuperTypes(String, String, Gets a description of user-defined type hierarchies Empty ResultSet


String) defined in a particular schema in this database object
getSuperTables(String, String, Gets a description of tables defined in a particular Empty ResultSet
String) schema in this database object

www.faircom.com
All Rights Reserved
65
Chapter 4
JDBC Conformance Notes

getAttributes(String, String, String, Gets a description of the given attribute of the given Empty ResultSet
String) type for a user-defined type that is available in the object
given schema and catalog

supportsResultSetHoldability(int) Does the database support the given result set True if result set
holdability holdability is ResultSet
.CLOSE_CURSORS_
AT_COMMIT,
otherwise False

getResultSetHoldability() Gets the default holdability of this ResultSet object Always returns
ResultSet.CLOSE_CU
RSORS_AT_COMMIT

getDatabaseMajorVersion() Gets the major version number of the underlying returns 9


database
getDatabaseMinorVersion() Gets the minor version number of the underlying returns 0
database
getJDBCMajorVersion() Gets the major JDBC version number of this driver returns 3

getJDBCMinorVersion() Gets the minor JDBC version number of this driver returns 0

getSQLStateType() Indicates whether the SQLStates returned by returns sqlState99


SQLException.getSQLState is X/Open SQL CLI or
SQL99

locatorsUpdateCopy() Indicates whether updates made to LOB are made “Driver does not
on a copy or directly to the LOB support this”Exception

supportsStatementPooling() Does the database support statement pooling False

4.3 Error Messages


The error messages generated by the driver, along with associated SQLSTATE and c-treeACE SQL
error code values, are documented in the c-treeACE SQL Reference Manual.

FairCom Corporation
Copyright 2015 FairCom Corporation
66
c-treeSQL
JDBC Developer's Guide

Glossary
add [an ODBC data source]
Make a data source available to ODBC through the Add operation of the ODBC Administrator utility.
Adding a data source tells ODBC where a specific database resides and which ODBC driver to use to
access it. Adding a data source also invokes a setup dialog box for the particular driver so you can
provide other details the driver needs to connect to the database.
ADMIN
The default owner name for all system tables in a c-treeACE SQL database. Users must qualify
references to system tables as ADMIN.tablename.
alias
A temporary name for a table or column specified in the FROM clause of an SQL query expression.
Also called correlation name. Derived tables and search conditions that join a table with itself must
specify an alias. Once a query specifies an alias, references to the table or column must use the alias
and not the underlying table or column name.
applet
A special kind of Java program whose compiled class files a Java-enabled browser can download
from the Internet and run.
ASCII
(American Standard Code for Information Interchange) A 7-bit character set that provides 128
character combinations.
bytecode
Machine-independent code generated by the Java compiler and executed by the Java interpreter.
candidate key
Another term for unique key.
cardinality
Number of rows in a result table.
Cartesian product
Also called cross-product. In a query expression, the result table generated when a FROM clause
lists more than one table but specifies no join conditions. In such a case, the result table is formed by
concatenating every row of every table with all other rows in all tables. Typically, Cartesian products
are not useful and are slow to process.
client

www.faircom.com
All Rights Reserved
67
Chapter 4
Glossary

Generally, in client/server systems, the part of the system that sends requests to servers and
processes the results of those requests.
collation
The rules used to control how character strings in a character set compare with each other. Each
character set specifies a collating sequence that defines relative values of each character for
comparing, merging and sorting character strings.
column alias
An alias specified for a column. See alias.
constraint
Part of an SQL table definition that restricts the values that can be stored in a table. When you insert,
delete, or update column values, the constraint checks the new values against the conditions
specified by the constraint. If the value violates the constraint, it generates an error. Along with
triggers, constraints enforce referential integrity by insuring that a value stored in the foreign key of a
table must either be null or be equal to some value in the matching unique or primary key of another
table.
correlation name
Another term for alias.
cross product
Another term for Cartesian product.
data dictionary
Another term for system catalog.
data source
See ODBC data source.
derived table
A virtual table specified as a query expression in the FROM clause of another query expression.
driver manager
See JDBC driver manager and ODBC driver manager.
foreign key
A column or columns in a table whose values must either be null or equal to some value in a
corresponding column (called the primary key) in another table. Use the REFERENCES clause in the
SQL CREATE TABLE statement to create foreign keys.
form of use
The storage format for characters in a character set. Some character sets, such as ASCII, require
one byte (octet) for each character. Others, such as Unicode, use two bytes, and are called
multi-octet character sets.
input parameter
In a stored procedure specification, an argument that an application must pass when it calls the
stored procedure. In an SQL statement, a parameter marker in the statement string that acts as a
placeholder for a value that will be substituted when the statement executes.
interface
In Java, a definition of a set of methods that one or more objects will implement. Interfaces declare
only methods and constants, not variables. Interfaces provide multiple-inheritance capabilities.

FairCom Corporation
Copyright 2015 FairCom Corporation
68
c-treeSQL
JDBC Developer's Guide

Java snippet
See snippet.
JDBC
Java Database Connectivity: a part of the Java language that allows applications to embed standard
SQL statements and access any database that implements a JDBC driver.
JDBC driver
Database-specific software that receives calls from the JDBC driver manager, translates them into a
form that the database can process, and returns data to the application.
JDBC driver manager
A Java class that implements methods to route calls from a JDBC application to the appropriate
JDBC driver for a particular JDBC URL.
join
A relational operation that combines data from two tables.
main-memory storage system / storage manager
A storage system and storage manager supplied with c-treeSQL. It provides a mechanism for
implementations to store data in memory instead of on disk. By using the main-memory storage
system for volatile data such as temporary sort tables and dynamic indexes, implementations can
improve performance of many queries, such as joins.
manager
A main component of the SQL engine. The SQL engine includes several managers, including the
SQL statement manager, parser, and optimizer.
metadata
Data that details the structure of tables and indexes in the c-tree Plus. The SQL engine stores
metadata in the system catalog.
octet
A group of eight bits. Synonymous with byte, and often used in descriptions of character-set encoding
format.
ODBC application
Any program that calls ODBC functions and uses them to issue SQL statements. Many vendors have
added ODBC capabilities to their existing Windows-based tools.
ODBC data source
In ODBC terminology, a specific combination of a database system, the operating system it uses, and
any network software required to access it. Before applications can access a database through
ODBC, you use the ODBC Administrator to add a data source -- register information about the
database and an ODBC driver that can connect to it -- for that database. More than one data source
name can refer to the same database, and deleting a data source does not delete the associated
database.
ODBC driver
Vendor-supplied software that processes ODBC function calls for a specific data source. The driver
connects to the data source, translates the standard SQL statements into syntax the data source can
process, and returns data to the application. c-treeSQL includes an ODBC driver that provides access
to the c-treeSQL Server.
ODBC driver manager

www.faircom.com
All Rights Reserved
69
Chapter 4
Glossary

A Microsoft-supplied program that routes calls from an application to the appropriate ODBC driver for
a data source.
optimizer
Within the SQL engine, the manager that analyzes costs and statistics associated with the statement
and converts the relational algebra tree to the most efficient form for execution. The optimizer stores
the trees for later use.
output parameter
In a stored procedure specification, an argument in which the stored procedure returns a value after it
executes.
package
A group of related Java classes and interfaces, like a class library in C++. The Java development
environment includes many packages of classes that procedures can import. The Java runtime
system automatically imports the java.lang package. Stored procedures must explicitly import other
classes by specifying them in the IMPORT clause of a CREATE PROCEDURE statement.
parameter marker
A question mark (?) in a procedure call or SQL statement string that acts as a placeholder for an input
or output parameter supplied at runtime when the procedure executes. The CALL statement (or
corresponding ODBC or JDBC escape clause) use parameter markers to pass parameters to stored
procedures, and the SQLIStatement, SQLPStatement, and SQLCursor objects use them within
procedures.
primary key
A subset of the fields in a table, characterized by the constraint that no two records in a table may
have the same primary key value, and that no fields of the primary key may have a null value.
Primary keys are specified in a CREATE TABLE statement.
procedure body
In a stored procedure, the Java code between the BEGIN and END keywords of a CREATE
PROCEDURE statement.
procedure result set
In a stored procedure, a set of data rows returned to the calling application. The number and data
types of columns in the procedure result set are specified in the RESULT clause of the CREATE
PROCEDURE statement. The procedure can transfer data from an SQL result set to the procedure
result set or it can store data generated internally. A stored procedure can have only one procedure
result set.
procedure specification
In a CREATE PROCEDURE statement, the clauses preceding the procedure body that specify the
procedure name, any input and output parameters, any result set columns, and any Java packages to
import.
procedure variable
A Java variable declared within the body of a stored procedure, as compared to a procedure input
parameter or output parameter, which are declared outside the procedure body and are visible to the
application that calls the stored procedure.
query expression
The fundamental element in SQL syntax. Query expressions specify a result table derived from some
combination of rows from the tables or views identified in the FROM clause of the expression. Query

FairCom Corporation
Copyright 2015 FairCom Corporation
70
c-treeSQL
JDBC Developer's Guide

expressions are the basis of SELECT, CREATE VIEW, and INSERT statements, and can be used in
some expressions and search conditions.
referential integrity
The condition where the value stored in a database table’s foreign key must either be null or be equal
to some value in another table’s the matching unique or primary key. SQL provides two mechanisms
to enforce referential integrity: constraints specified as part of CREATE TABLE statements prevent
updates that violate referential integrity, and triggers specified in CREATE TRIGGER statements
execute a stored procedure to enforce referential integrity.
repertoire
The set of characters allowed in a character set.
result set
In a stored procedure, either an SQL result set or a procedure result set. More generally, another
term for result table.
result table
A virtual table of values derived from columns and rows of one or more tables that meet conditions
specified by an SQL query expression.
row identifier
Another term for tuple identifier.
search condition
The SQL syntax element that specifies a condition that is true or false about a given row or group of
rows. Query expressions and UPDATE statements can specify a search condition. The search
condition restricts the number of rows in the result table for the query expression or UPDATE
statement. Search conditions contain one or more predicates. Search conditions follow the WHERE
or HAVING keywords in SQL statements.
selectivity
The fraction of a table’s rows returned by a query.
server
Generally, in client/server systems, the part of the system that receives requests from clients and
responds with results to those requests.
snippet
In a stored procedure, the sequence of Java statements between the BEGIN and END keywords in
the CREATE PROCEDURE (or CREATE TRIGGER) statement. The Java statements become a
method in a class the SQL engine creates and submits to the Java compiler.
SQL diagnostics area
A data structure that contains information about the execution status (success, error or warning
conditions) of the most recent SQL statement. The SQL-92 standard specified the diagnostics area
as a standardized alternative to widely varying implementations of the SQLCA. c-treeSQL supports
both the SQLCA and the SQL diagnostics area. The SQL GET DIAGNOSTICS statement returns
information about the diagnostics area to an application, including the value of the SQLSTATE status
parameter.
SQL engine
The core component of the c-treeACE SQL environment. The SQL engine receives requests from
applications, processes them, and returns results. The SQL engine conveys requests to the c-tree
Plus engine.

www.faircom.com
All Rights Reserved
71
Chapter 4
Glossary

SQLCA
SQL Communications area: A data structure that contains information about the execution status
(success, error or warning conditions) of the most recent SQL statement. The SQLCA includes an
SQLCODE field. The SQLCA provides the same information as the SQL diagnostics area, but is not
compliant with the SQL-92 standard. c-treeSQL supports both the SQLCA and the SQL diagnostics
area.
SQLCODE
An integer status parameter whose value indicates the condition status returned by the most recent
SQL statement. An SQLCODE value of zero means success, a positive value means warning, and a
negative value means an error status. SQLCODE is superseded by SQLSTATE in the SQL-92
standard. Applications declare either SQLSTATE or SQLCODE, or both. SQL returns the status to
SQLSTATE or SQLCODE after execution of each SQL statement.
SQL result set
In a stored procedure, the set of data rows generated by an SQL statement (SELECT and, in some
cases, CALL).
SQLSTATE
A 5-character status parameter whose value indicates the condition status returned by the most
recent SQL statement. SQLSTATE is specified by the SQL-92 standard as a replacement for the
SQLCODE status parameter (which was part of SQL-89). SQLSTATE defines many more specific
error conditions than SQLCODE, which allows applications to implement more portable error
handling. Applications declare either SQLSTATE or SQLCODE, or both. SQL returns the status to
SQLSTATE or SQLCODE after execution of each SQL statement.
stored procedure
A snippet of Java source code embedded in an SQL CREATE PROCEDURE statement. The source
code can use all standard Java features as well as use c-treeSQL-supplied Java classes for
processing any number of SQL statements.
system catalog
Tables created by the SQL engine that store information about tables, columns, and indexes that
make up the database. The SQL engine creates and manages the system catalog.
system tables
Another term for system catalog.
tid
Another term for tuple identifier.
transaction
A group of operations whose changes can be made permanent or undone only as a unit to protect
against data corruption.
trigger
A special type of stored procedure that helps insure referential integrity for a database. Like stored
procedures, triggers also contain Java source code (embedded in a CREATE TRIGGER statement)
and use c-treeSQL Java classes. However, triggers are automatically invoked (“fired”) by certain SQL
operations (an insert, update, or delete operation) on the trigger’s target table.
trigger action time
The BEFORE or AFTER keywords in a CREATE TRIGGER statement. The trigger action time
specifies whether the actions implemented by the trigger execute before or after the triggering
INSERT, UPDATE, or DELETE statement.

FairCom Corporation
Copyright 2015 FairCom Corporation
72
c-treeSQL
JDBC Developer's Guide

trigger event
The statement that causes a trigger to execute. Trigger events can be SQL INSERT, UPDATE, or
DELETE statements that affect the table for which a trigger is defined.
triggered action
The Java code within the BEGIN END clause of a CREATE TRIGGER statement. The code
implements actions to be completed when a triggering statement specifies the target table.
tuple identifier
A unique identifier for a tuple (row) in a table. The SQL scalar function ROWID and related functions
return tuple identifiers to applications.
Unicode
A superset of the ASCII character set that uses two bytes for each character rather than ASCII's 7-bit
representation. Able to handle 65,536 character combinations instead of ASCII's 128, Unicode
includes alphabets for many of the world's languages. The first 128 codes of Unicode are identical to
ASCII, with a second-byte value of zero.
unique key
A column or columns in a table whose value (or combination of values) must be unique. Use the
UNIQUE clause of the SQL CREATE TABLE statement to create unique keys. Unique keys are also
called candidate keys.
URL
In general, a Universal Resource Locater used to specify protocols and locations of items on the
Internet. In JDBC, a database connection string in the form jdbc:subprotocol:subname. The
c-treeSQL JDBC Driver format for database URLs is jdbc:ctree:6597@host_name:db_name.
view
A virtual table that recreates the result table specified by a SELECT statement. No data is stored in a
view, but other queries can refer to it as if it were a table containing data corresponding to the result
table it specifies.
virtual table
A table of values that is not physically stored in a database, but instead derived from columns and
rows of other tables. SQL generates virtual tables in its processing of query expressions: the FROM,
WHERE, GROUP BY and HAVING clauses each generate a virtual table based on their input.
virtual machine
The Java specification for a hardware-independent and portable language environment. Java
language compilers generate code that can execute on a virtual machine. Implementations of the
Java virtual machine for specific hardware and software platforms allow the same compiled code to
execute without modification.

www.faircom.com
All Rights Reserved
73
Error messages...................................................... 66
Error Messages...................................................... 66
Index F
FairCom Typographical Conventions ....................... v
G
A
getXXX ................................................................... 55
Additional Resources ............................12, 24, 33, 45
method ............................................................... 55
An Example Connection ......................................... 51
Glossary ................................................................. 67
API, JDBC ................................................................. 1
Applet ...................................................................... 48 I
Application server ................................................... 48 Implementation in c-treeACE SQL JDBC Driver ... 52
driver files ........................................................... 49 Init .......................................................... 7, 15, 27, 35
Architecture, JDBC ................................................... 1 Internet Explorer .................................................... 47
Authentication detail ............................................... 50 Introduction ........................................................ 1, 47
Introductory Tutorial ..................................................6
B
Basic JDBC Driver Operations ............................... 47 J
Bridge drivers ............................................................ 2 JAR file ................................................................... 47
Java Archive file ..................................................... 47
C
Java URL connection string ................................... 50
Class files location .................................................. 48
Java URL Connection String ................................. 50
Class.forName ........................................................ 50
java.sql ......................................................................1
Connect to the JDBC Driver Using
JavaSoft JDK Version 1.1.3 (Windows) ................. 47
DriverManager.GetConnection ........................... 50
JavaSoft JDK Version 1.1.5 (UNIX) ....................... 47
Connecting to a database ....................................... 49
javax.sql Package .................................................. 51
Connecting to a Database ................................47, 49
JDBC .........................................................................1
Connection
applet ................................................................. 47
example .............................................................. 51
application server ............................................... 48
Connection Pooling................................................. 52
architecture ...........................................................1
Connection Pooling Support in JDBC..................... 51
class files location .............................................. 48
Connection string .................................................... 50
comparison to ODBC ............................................3
Copying JDBC Driver and Applet Class Files ........ 48
connect to a database ....................................... 49
Copying JDBC Driver Files to the Application Server
c-treeSQL JDBC driver .........................................3
(If Necessary) ..................................................... 49
driver files ........................................................... 49
Creating a Web Page That Invokes the Applet ...... 48
driver manager ......................................................1
c-treeSQL JDBC driver ............................................. 3
driver setup ........................................................ 47
D drivers ...................................................................2
Database connection environment variables ........................................ 49
example .............................................................. 51 error messages .................................................. 66
Database connectivity............................................. 49 performance ....................................................... 52
DatabaseMetaData ................................................. 56 setup .................................................................. 47
return values ....................................................... 56 type 1 driver ..........................................................2
Define .....................................................8, 16, 28, 36 type 2 driver ..........................................................3
DhJDBCApplet.class .............................................. 48 type 3 driver ..........................................................3
DhJDBCTest.jar ...................................................... 48 type 4 driver ..........................................................3
Done .....................................................11, 23, 32, 44 JDBC Architecture ....................................................1
Driver files ............................................................... 49 JDBC Compared to ODBC .......................................3
Driver Manager JDBC Conformance Notes .................................... 55
JDBC .................................................................... 1 JDBC Version Information ..................................... 53
Driver Socket SEND/RECV Timeout ...................... 53 JDBC-ODBC Bridge Drivers .....................................2
Driver, types of .......................................................... 2
L
DriverManager.GetConnection ............................... 50
Load the JDBC Driver Using Class.forName ......... 50
E
M
Environment variables ............................................ 49
Manage .................................................. 9, 19, 29, 39

www.faircom.com
All Rights Reserved
75
Managing Transactions Explicitly to Improve U
Performance ....................................................... 52 UNIX
environment variables ........................................ 49
N
URL connection string ........................................... 50
Native-Method drivers............................................... 3
User authentication detail ...................................... 50
Native-Method Drivers .............................................. 3
User Authentication Detail ..................................... 50
Native-Protocol All-Java Drivers (c-treeSQL JDBC
Using A DataSource Object To Make A Connection
Driver) ................................................................... 3
........................................................................... 51
Native-Protocol All-Java drivers (c-treeSQL) ........... 3
Netscape ................................................................. 47 V
Network-Protocol All-Java Drivers ............................ 3 Virtual machine ...................................................... 47
Network-Protocol All-Jave drivers ............................ 3
W
O Web page ............................................................... 48
Object Web Server ............................................................ 47
Properties ........................................................... 50 Windows NT
ODBC envrionment variables ........................................ 49
compared to JDBC ............................................... 3
Overview ................................................................... 1
P
Performance improvements ................................... 52
PreparedStatement.setXXX ................................... 55
Properties object ..................................................... 50
Q
Query Timeout Options .......................................... 53
Quick Tour ................................................................ 5
R
Record/Row Locking............................................... 25
Relationships .......................................................... 13
Required Java Environment ................................... 47
Required software ................................................... 47
Return values .......................................................... 56
Return Values for DatabaseMetaData Methods ..... 56
Running the Sample Application ............................ 49
S
Setting Environment Variables ............................... 49
Setting up the c-treeSQL JDBC Driver ................... 47
Setting Up the JDBC Driver
Application Server............................................... 48
Web Server ......................................................... 47
setXXX .................................................................... 55
Supported Data Types ............................................ 55
T
Transaction management ....................................... 52
Transaction Processing .......................................... 34
Type 1 JDBC driver .................................................. 2
Type 2 JDBC driver .................................................. 3
Type 3 JDBC driver .................................................. 3
Type 4 JDBC driver .................................................. 3
Types of JDBC drivers .............................................. 2
Types of JDBC Drivers ............................................. 2

FairCom Corporation
Copyright 2015 FairCom Corporation
76

You might also like