Sunteți pe pagina 1din 132

SQLBase

20-6245-0001

Guide to Connecting to SQLBase

Trademarks
GUPTA, SQLBase, SQLRouter, Team Developer, and SQLTalk are trademarks of Gupta Technologies, LLC registered in the United States and/or other countries. SQLWindows is a registered trademark of Microsoft Corporation, and is used under license to Gupta Technologies, LLC. Centura and Centura Software are registered trademarks of Centura Software Corporation, and are used under license to Gupta Technologies, LLC. Team Object Manager, Web Developer, QuickObjects, Object Nationalizer, Report Builder, Connectivity Administrator, Development Kit, Component Development Kit, SQLBase Resource Manager, and SQLConsole are names of products from Gupta Technologies, LLC. Adobe is a trademark of Adobe Systems, Incorporated. IBM, OS/2, NetBIOS, and AIX are registered trademarks of International Business Machines Corporation. Linux is a trademark of Linus Torvalds. Red Hat is a trademark of Red Hat, Incorporated. Novell and Netware are trademarks of Novell, Inc. SUSE is a trademark of SUSE LINUX AG. Java, JavaScript, and Solaris are trademarks of Sun Microsystems, Incorporated. Microsoft, Outlook, PowerPoint, Visual C++, Visual Studio, Internet Explorer, Internet Information Server, DOS, Win 32, Windows, ActiveX, MSDN, SQL Server, and Visual Basic are either registered trademarks or trademarks of Microsoft Corporation in the United States of America and/or other countries. Netscape FastTrack and Navigator are trademarks of Netscape Communications Corporation. All other product or service names mentioned herein are trademarks or registered trademarks of their respective owners.

Copyright
Copyright 2005 by Gupta Technologies LLC. All rights reserved. 20-6245-0001 April 2005

Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
Audience. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10 Notation conventions . . . . . . . . . . . . . . . . . . . . . 1-10 Other helpful resources . . . . . . . . . . . . . . . . . . . 1-11 Send comments to.... . . . . . . . . . . . . . . . . . . . . . 1-11

1 Introduction to SQLBase Connectivity. 1-1


Gupta client and server technology. . . . . . . . . . . . . . . 1-1 SQL.INI and the Connectivity Administrator . . . . . . . . 1-2 Running Connectivity Administrator . . . . . . . . . . . 1-2 SQL.INI server-side example . . . . . . . . . . . . . . . . 1-9 SQL.INI client-side example . . . . . . . . . . . . . . . . 1-11 SQLBase native connectivity . . . . . . . . . . . . . . . . . . 1-11 General features of SQLBase . . . . . . . . . . . . . . . . . . 1-12 DML and DDL . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 Making a connection. . . . . . . . . . . . . . . . . . . . . . 1-12 Bind variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 Isolation levels . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14 Long character and long binary data handling . . 1-15 Stored procedures and triggers . . . . . . . . . . . . . 1-15

-3

2 ODBC Driver Introduction . . . . . . . . . . . . . . 2-1


How does it work?. . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 ODBC overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 About the SQLBase ODBC driver for Windows . . . . . 2-3 System requirements . . . . . . . . . . . . . . . . . . . . . . 2-3 About the SQLBase ODBC driver for Linux . . . . . . . . 2-3 System requirements . . . . . . . . . . . . . . . . . . . . . . 2-3 Supported Features . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4 ODBC Conformance Level . . . . . . . . . . . . . . . . . . 2-4 Number of Connections and Statements Supported2-4 Isolation and Lock Levels Supported . . . . . . . . . . 2-4 Supported ODBC Functions . . . . . . . . . . . . . . . . . 2-5 Deprecated functions . . . . . . . . . . . . . . . . . . . . . . 2-6 Configuring Data Sources in Windows . . . . . . . . . . . . 2-7 Data Source Properties dialog . . . . . . . . . . . . . . . 2-8 Configuring Data Sources in Linux . . . . . . . . . . . . . . . 2-9 Driver manager configuration files . . . . . . . . . . . . 2-9 Changing configuration information . . . . . . . . . . . 2-9 How-to information for ODBC . . . . . . . . . . . . . . . . . . 2-11 How do SQLBase datatypes map to ODBC datatypes?2-11 How do I start a transaction? . . . . . . . . . . . . . . . 2-12 How do I set isolation levels? . . . . . . . . . . . . . . . 2-12 How do I read and write long character and long binary data? 2-12 How do I run stored procedures? . . . . . . . . . . . . 2-14

3 Making an ODBC Connection

. . . . . . . . . 3-1

Connection strings . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1 Connection string keywords . . . . . . . . . . . . . . . . . 3-1 Logon dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 Linux connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3 PHP example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3

4 Introducing SQLBase OLE DB Data Provider4-4

1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 OLE DB components . . . . . . . . . . . . . . . . . . . . . . 4-2 Recommended reading . . . . . . . . . . . . . . . . . . . . 4-2 About SQLBase OLE DB Data Provider . . . . . . . . . . . 4-2 SQLBase OLE DB Data Provider name . . . . . . . . 4-4 Data source name . . . . . . . . . . . . . . . . . . . . . . . . 4-4 Supported programming tools . . . . . . . . . . . . . . . 4-4 How-to information for the OLE DB provider. . . . . . . . 4-4 How do SQLBase datatypes map to OLE DB datatypes?4-4 How do I start a transaction? . . . . . . . . . . . . . . . . 4-4 How do I set isolation levels? . . . . . . . . . . . . . . . . 4-5 How do I use long character data and long binary data?4-5 ADO Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6 ADO features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6 Remote Data Service . . . . . . . . . . . . . . . . . . . . . . 4-7 Programming with ADO . . . . . . . . . . . . . . . . . . . . 4-7 Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 ADO Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 Dynamic Properties Collections . . . . . . . . . . . . . . 4-9 Working with Data. . . . . . . . . . . . . . . . . . . . . . . . . 4-9 SQLBase provider-specific dynamic properties . 4-10 Sample applications . . . . . . . . . . . . . . . . . . . . . . 4-10 Connecting to data through the Provider . . . . . . . . . 4-11 Establishing a connection using ADO . . . . . . . . . . . . 4-11 Coding Sample using ADO. . . . . . . . . . . . . . . . . 4-12

5 Supported OLE DB COM Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1


Supported COM objects . . . . . . . . . . . . . . . . . . . . . . . 5-2 Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5 Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6

-5

Rowset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8 Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9

6 ADO Mapping to Gupta . . . . . . . . . . . . . . . . 6-1


Isolation level mapping . . . . . . . . . . . . . . . . . . . . . . . . 6-2 ADO mapping to Gupta interfaces . . . . . . . . . . . . . . . 6-2 Command object mapping . . . . . . . . . . . . . . . . . . . . . 6-3 Connection object mapping. . . . . . . . . . . . . . . . . . . . . 6-3 Error object mapping. . . . . . . . . . . . . . . . . . . . . . . . . . 6-4 Field object mapping . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5 Parameter object mapping . . . . . . . . . . . . . . . . . . . . . 6-6 Recordset object mapping . . . . . . . . . . . . . . . . . . . . . 6-7

7 .NET Data Provider. . . . . . . . . . . . . . . . . . . . . 7-1


SQLBase .NET requirements . . . . . . . . . . . . . . . . . . . 7-1 SQLBase .NET implementation . . . . . . . . . . . . . . . . . 7-1 How-to information for the .NET data provider . . . . . . 7-2 How do SQLBase datatypes map to CLR datatypes?7-2 How do I start a transaction? . . . . . . . . . . . . . . . . 7-3 How do I set isolation levels? . . . . . . . . . . . . . . . . 7-3 How do I use long character data and long binary data?7-3 How do I run stored procedures? . . . . . . . . . . . . . 7-5 SQLBaseConnection object . . . . . . . . . . . . . . . . . . . . 7-6 SQLBaseConnection properties . . . . . . . . . . . . . . 7-6 SQLBaseConnection methods . . . . . . . . . . . . . . . 7-6 SQLBaseCommand object . . . . . . . . . . . . . . . . . . . . . 7-8 SQLBaseCommand properties. . . . . . . . . . . . . . . 7-9 SQLBaseCommand methods . . . . . . . . . . . . . . . . 7-9 SQLBaseDataReader object. . . . . . . . . . . . . . . . . . . 7-10 SQLBaseDataReader methods . . . . . . . . . . . . . 7-10 Get... methods . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10 Get methods for long (BLOB) data . . . . . . . . . . . 7-11 GetDataTypeName. . . . . . . . . . . . . . . . . . . . . . . 7-11 GetFieldType . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11 -6

GetName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12 GetOrdinal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12 GetValues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12 IsDbNull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12 NextResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12 SQLBaseDataAdapter object . . . . . . . . . . . . . . . . . . 7-13 SQLBaseDataAdapterProperties . . . . . . . . . . . . 7-13 SQLBaseTransaction object . . . . . . . . . . . . . . . . . . . 7-14 SQLBaseTransaction Properties . . . . . . . . . . . . 7-14 SQLBaseTransaction methods. . . . . . . . . . . . . . 7-14 SQLBaseParameter object . . . . . . . . . . . . . . . . . . . . 7-14 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14 SQLBaseParameters object . . . . . . . . . . . . . . . . . . . 7-15 Add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15 SQLBaseException object . . . . . . . . . . . . . . . . . . . . 7-16 SQLBaseException Properties . . . . . . . . . . . . . . 7-16 SQLBase classes and transaction state . . . . . . . . . . 7-16

8 Introduction to the JDBC driver . . . . . . . . 8-1


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1 JDK Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2 Tested Platforms. . . . . . . . . . . . . . . . . . . . . . . . . . 8-2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2 CLASSPATH . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2 Server Configuration. . . . . . . . . . . . . . . . . . . . . . . 8-3 SQLBase Support for JDBC . . . . . . . . . . . . . . . . . . . . 8-3 SQL Operations Support . . . . . . . . . . . . . . . . . . . 8-3 DDL Operations Support . . . . . . . . . . . . . . . . . . . 8-3 DML Operations Support . . . . . . . . . . . . . . . . . . . 8-3 Multiple Connection Support. . . . . . . . . . . . . . . . . 8-3 Multi-threading Support . . . . . . . . . . . . . . . . . . . . 8-3 Transaction Model . . . . . . . . . . . . . . . . . . . . . . . . 8-4

-7

How-to information for the JDBC driver . . . . . . . . . . . 8-4 How do SQLBase datatypes map to JDBC datatypes?8-4 How do I start a transaction? . . . . . . . . . . . . . . . . 8-5 How do I set isolation levels? . . . . . . . . . . . . . . . . 8-5 How do I use long character data and long binary data?8-5 How do I run stored procedures? . . . . . . . . . . . . . 8-6 URL formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6 URL keywords: . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6 Data types and conversions . . . . . . . . . . . . . . . . . . . . 8-6 SQLBase Supported Data Types:. . . . . . . . . . . . . . . . 8-8 For READING Operations using ResultSet: . . . . 8-8 Datatypes example . . . . . . . . . . . . . . . . . . . . . . . . 8-9 Bind variable support . . . . . . . . . . . . . . . . . . . . . . . . 8-11 Stored procedure support . . . . . . . . . . . . . . . . . . . . . 8-11 Stored procedure example . . . . . . . . . . . . . . . . . 8-11 Named Cursor Support . . . . . . . . . . . . . . . . . . . . . . . 8-13 Error Message Support . . . . . . . . . . . . . . . . . . . . . . . 8-13 Application and Applet Development . . . . . . . . . . . . 8-13 Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-14

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . Glossary-1 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Index-1

-8

Guide to Connecting to SQLBase

Preface
This manual provides reference information about using database drivers and data providers to access SQLBase from programming tools, such as Microsoft Visual Basic, C++, Java, and Delphi. This preface provides the following information: Who should read this manual. The organization of this manual. The documentation format. The notation conventions used in this manual. Related publications.

Guide to Connecting to SQLBase

-9

Preface

Audience
This manual is intended for Application Developers building client applications that access Gupta SQLBase using frontend products such as Visual Basic, C++, and Delphi. This manual assumes you have a working knowledge of SQLBase, relational databases in general, and SQL.

Notation conventions
Before you start using this manual, it is important to understand the typographical conventions we use in this manual:
Formatting Convention You User bold type Courier 9 SQL.INI MAPDLL.EXE Precaution Vital information Supplemental information Alt+1 Warning: Important: Note: A plus sign between key names means to press and hold down the first key while you press the second key Type of Information A developer who reads this manual The end-user of applications that you write Menu items, push buttons, and field names. Things that you select. Keyboard keys that you press. Development language code example Program names and file names

-10

Guide to Connecting to SQLBase

Other helpful resources


Gupta Books Online. The Gupta document suite is available online. This document collection lets you perform full-text indexed searches across the entire document suite, navigate the table of contents using the expandable/collapsible browser, or print any chapter. Open the collection by selecting the Gupta Books Online icon from the Start menu or by double-clicking on the launcher icon in the program group. World Wide Web. Gupta Technologies LLCs world wide Web site contains information about Gupta Technologies LLCs partners, products, sales, support, training, and users. The URL is http://www.guptaworldwide.com. The technical services section of our Web site is a valuable resource for customers with technical support issues, and addresses a variety of topics and services, including technical support case status, commonly asked questions, access to Guptas online newsgroups, links to shareware tools, product bulletins, white papers, and downloadable product updates. Our Web site also includes information on training, including course descriptions, class schedules, and certified training partners.

Send comments to...


If you have any comments or suggestions regarding this manul, please send them to: Technical Publications Department Gupta Technologies 975 Island Drive Redwood Shores, CA 94065 or send email, with comments or suggestions to: techpubs@guptaworldwide.com

Guide to Connecting to SQLBase

-11

Connecting to SQLBase

Chapter 1

Introduction to SQLBase Connectivity


Gupta client and server technology
Connectivity has two faces at Gupta Technologies. Gupta publishes SQLBase, the relational database server discussed in this book. And we also publish Team Developer, a set of tools for creating powerful client applications that connect to SQLBase and to many other data sources as well. The details of client connectivity for applications written with Team Developer to any data source are documented in another Gupta book, Connecting Gupta Objects to Databases. In contrast, the book you are reading now will discuss how to connect any client application, written with any programming tool, to Gupta SQLBase. But the database administrator still needs to be concerned with client connectivity, for two reasons: You need client tools for DBA tasks like configuration, backup, and testing. Since you are likely to use Guptas tools for these purposes, you will still need to have some knowledge of client connectivity. Client computers, even those that do not use Gupta client tools, still need at least a rudimentary client-side SQL.INI file on their machines, for purposes of specifying basic server, database and protocol information.

Connecting to SQLBase

1-1

Chapter 1

Introduction to SQLBase Connectivity

SQL.INI and the Connectivity Administrator


Both Guptas client tools and their server tools use a configuration file to store connectivity information. In versions of SQLBase prior to 8.5, this file was always named SQL.INI, and choices for its location were limited. In version 8.5 the file name and location are now under your control, although the default name is still SQL.INI, and that is the name we use to refer to the configuration file in Gupta documentation. The ability to have any name and location for the configuration file is a feature that supports multiple concurent SQLBase installations on a single computer, also new in version 8.5. For new SQLBase installations, SQL.INI is created during the install process and is tailored to your answers to the install questions. By default, it is found in the same directory as the SQLBase executables. This default SQL.INI file is functional immediately and, for many users, it is unnecessary to ever change SQL.INI until new servers or new databases are added to the installation. Experienced users may wish to change SQL.INI settings to achieve specific performance and communication goals. The remaining chapters in this book will discuss how to configure SQLBase drivers and data providers. In some cases such configuration involves changes to SQL.INI. Even in cases where SQL.INI is not directly involved, such as the OLE DB data provider, it is still indirectly involved since individual databases must be registered in SQL.INI before they are accessible to client applications. Although SQL.INI can be modified with a text editor such as Notepad, uncontrolled manual changes can accidentally introduce problems, such as being unable to use a specific protocol against SQLBase or being unable to access a particular database. Gupta recommends that when possible you use the Connectivity Administrator instead to make changes. In this book, we discuss only basic SQL.INI concepts. The Database Administrators Guide contains much more detailed information about every concept that is briefly discussed in this chapter.

Running Connectivity Administrator


Connectivity Administrator is one of the options in the Gupta program group. Depending on what you have installed, the main window can show two tabs. The Connectivity tab works on client-side settings to add or remove, enable or disable routers and protocols. Choose the Server tab to add or remove databases and enable or disable protocols. When configuring connectivity for a SQLBase server, you can: 1-2 Set up the options for a SQLBase server Enable and disable communication protocols

Connecting to SQLBase

SQL.INI and the Connectivity Administrator

Modify the listening protocols of a database name Add or remove a server name from a listening protocol Add or remove a database name View a list of database names Change the settings of an installed server

When configuring connectivity for a SQLBase client, you can: Edit the name, encryption level, and runtime directory of the client itself. Enable and disable listening protocols. Edit the properties of some listening protocols (TCP/IP and local connection) Associate new server names with a specific listening protocol, or remove server names from a listening protocol. Limit access to specific databases on a server, or access all databases. Change properties of a server/protocol combination, such as the TCP/IP listen port. Enable, disable, and configure data sources other than SQLBase. (That topic is related to Gupta Team Developer and is outside the scope of this book; see Connecting Gupta Objects to Databases.)

Connecting to SQLBase

1-3

Chapter 1

Introduction to SQLBase Connectivity

The illustration below shows how the Client tab allows you to change the name and location of the configuration file you wish to edit, by directly typing the name or by clicking the Browse pushbutton..

1-4

Connecting to SQLBase

SQL.INI and the Connectivity Administrator

On both tabs, you left-click to select an item, double-click to change properties, or right-click to display a menu of connectivity functions.

Connecting to SQLBase

1-5

Chapter 1

Introduction to SQLBase Connectivity

If you double-click on the server node (server1 above), or right-click on it and choose Properties, you can work with the Server Configuration dialog box, which has three tabs:

The Basic tab controls the server name. The name you use in SQL.INI files on client computers must match the name found here.

1-6

Connecting to SQLBase

SQL.INI and the Connectivity Administrator

The Optional tab allows you to configure other commonly-changed and critical settings.

Connecting to SQLBase

1-7

Chapter 1

Introduction to SQLBase Connectivity

The Advanced tab allows you to change any server keyword, presuming that you know the value that should be associated with the keyword. Detailed information about values and keywords is available in Chapter 3 of the Database Administrators Guide.

1-8

Connecting to SQLBase

SQL.INI and the Connectivity Administrator

You can also configure database settings, by double-clicking on a database node or by right-clicking it and then choosing Properties.

Database setting changes are limited to the database name and activating/deactivating listening protocols. Note that in the example above, three of the listening protocol checkboxes are disabled. That is because those protocols have been disabled at the server level, so they cannot be manipulated at the database level. You can add a new database to the server by right-clicking the Databases node, then choosing Add database.

SQL.INI server-side example


Shown below is a portion of a typical SQL.INI file containing basic information about a SQLBase server and its databases. Some of the lines in the file are annotated to explain their purpose.
[dbntsrv]

dbntsrv is the abbreviation for the SQLBase unlimited-user version section. Your version might be different. For example, the 10-user version uses the abbreviation dbnt10sv.
servername=server1,sqlmpipe,sqlws32

The default name for a SQLBase server is server1. Following the server name are the names of the listening protocols that apply to the entire server. (As we will see later, individual databases need not implement all of these protocols.) sqlmpipe represents the MTS (COM+) listener, and sqlws32 is the TCP/IP listener. These keywords are not case-sensitive.
dbname=ISLAND,SQLMPIPE,sqlws32

Connecting to SQLBase

1-9

Chapter 1

Introduction to SQLBase Connectivity

ISLAND is the demonstration/tutorial database installed with SQLBase. By default, it is assigned the same listening protocols as the server itself. Each database in a server must have a dbname line within the server section of SQL.INI.
cache=2000 sortcache=2000 readonly=0 oracleouterjoin=0 logfileprealloc=0 partitions=0 optimizerlevel=2 locktimeout=275 dbdir=C:\Program Files\Gupta

Databases are physical files, each in its own subdirectory with the same name as the database itself. By default, these subdirectories are presumed to be located under the SQLBase program directory, but you can change the path to point elsewhere.
dbname=SQLCON,sqlws32

Database SQLCON is used for the SQLConsole DBA utility. Note that in this example it implements only the TCP/IP listenting protocol, not the MTS protocol.
dbname=PURPLE,sqlmpipe,sqlws32

Database PURPLE was added using Connectivity Administrator. Note that it implements both of the listening protocols used by the server itself.
[dbntsrv.dll] comdll=sqlmpipe comdll=sqlws32

Section dbntsrv.dll determines which listening protocols will be loaded when the SQLBase server starts.
[dbntsrv.ws32] listenport=2155

Each listening protocol has a separate section in SQL.INI with optional extra information. The TCP/IP listener has a default port, 2155. You can override this, but if you do, you must insure that any SQL.INI files on client machines are altered to match the new port number.
Note: The default port for the MTS (COM+) listening protocol, SQLMPIPE, is 2156. This is not subject to overriding in SQL.INI - the port number is a runtime parameter that you supply to the SQLBase Resource Manager, SQLBrm.exe. For more information, see the SQLBase release notes. You can override this, but if you do, you must insure that any SQL.INI files on client machines are altered to match the new port number.

1-10 Connecting to SQLBase

SQLBase native connectivity

SQL.INI client-side example


This is a good spot to illustrate how SQL.INI files on client machines must match the SQL.INI on the server. Here are a few selected sections from SQL.INI on a client machine.
[win32client.dll] comdll=sqlws32

The [winclient32.dll] section shows the communication libraries that the client loads when it first tries to connect to a database. sqlws32, as with the server, indicates the TCP/IP listening protocol. This client is going to take part in MTS transactions, so you might expect to see a comdll=sqlmpipe line in this section as we did when discussing the server. However, sqlmpipe is only used on the server. Clients use TCP/ IP for both ordinary database communications and MTS transactions, so only the sqlws32 line is required in this case.
[win32client.ws32] serverpath=server1,devsrvr,2156/*

The [win32client.ws32] section provides more detail about the TCP/IP listening protocol. In the serverpath line, we see the name of the server (server1), which must match the name used in the SQL.INI file on the server machine. Then we see the name of the computer that hosts the SQLBase server (devsrvr). Then we see the listening port (2156). In this example, the SQLBase server is running the SQLMPIPE protocol for MTS (COM+) compatibility. Therefore the client SQL.INI points to the SQLMPIPE port, 2156, rather than the default TCP/IP port of 2155. If you change this port number to 2155, the client will still be able to communicate with the SQLBase server using TCP/IP, but will be unable to participate in MTS transactions. In any case, the port numbers used by the client SQL.INI file must match those used in the server SQL.INI file. Finally, the /* following the port number means that all databases on server1 are visible to the client. If you specified only one database name, such as 2156/ISLAND, then only that database would be visible to the client. The serverpath line is the only way that the client can determine how to reach the server, so its presence is critical. There can be multiple serverpath lines in this section, each pointing to different servers or different databases.

SQLBase native connectivity


This book discusses industry-standard drivers and database providers for SQLBase. In addition, SQLBase has native connectivity that can be used easily by Gupta client tools, and can be called from other client tools through an API. For more information about this native protocol, read the SQL Application Programming Interface book.

Connecting to SQLBase

1-11

Chapter 1

Introduction to SQLBase Connectivity

General features of SQLBase


SQLBase has a feature set that is largely consistent regardless of which driver or data provider is being used to communicate with it. However, there are slight differences in the feature set available to some drivers and data providers. Those differences will be noted individually in the chapters that describe the drivers and data providers. In this chapter, the general features of SQLBase are described. If you are interested in the most detailed information, refer to the SQL Language Reference book:

DML and DDL


SQLBase supports all commonly used Data Manipulation Language commands and Data Definition Language commands. For a summarized list of commands, see the SQL Command Reference chapter in the SQL Language Reference..

Making a connection
In the SQLBase native API, you can make "implicit" connections, meaning that multiple database cursors might be assigned to a single database connection. With implicit connections, changing the isolation level of a connection forces a COMMIT. Also, doing a COMMIT on one cursor will usually cause a COMMIT to occur for all other cursors sharing that connection, unless your application takes specific steps to prevent this. For more detailed information, see the chapter Using the SQL/API in the SQL Application Programming Interface Guide. However, all SQLBase drivers and data providers use "explicit" connections. This means that transactions performed against one connection will have no effect upon the transaction status of other connections.

Bind variables
SQLBase supports bind variables. A bind variable is a colon followed by a number or a string, in a position in a query where one would otherwise use literal data. The number or string corresponds to a variable in the client application running the query.

Datatypes
Here are the native datatypes supported by SQLBase:
Type Length 1 to 254 bytes

CHAR (or VARCHAR)

String

1-12 Connecting to SQLBase

General features of SQLBase

Type

Length 255 bytes to 2 gigabytes

LONG (or LONG VARCHAR) NUMBER DECIMAL (or DEC) INTEGER (or INT)

String (can be used for binary data too) Number Number Number

Up to 22 digits Up to 15 digits, including scale digits Up to 10 digits of precision, range -2147483648 to +2147483647 Up to 5 digits of precision, range -32768 to 32767 Double-precision floating point numbers, up to 22 digits. Up to 22 digits of precision, including scale digits Single-precision floating point numbers, up to 21 digits Number representing both a date value and time value. Like DATETIME, but only the date portion of the value is returned Like DATETIME, but only the time portion of the value is returned

SMALLINT DOUBLE PRECISION FLOAT REAL DATETIME (or TIMESTAMP) DATE

Number Number

Number Number Date/time

Date/time

TIME

Date/time

Detailed descriptions of these datatypes are available in the SQL Elements chapter of the SQL.Language Reference. There are significant differences between these datatypes and the sets of datatypes used in drivers and providers. The individual chapters following this one will detail the differences.

Isolation levels
Isolation levels are used to strike a balance between concurrency (allowing many users to share data) and consistency (insuring that data has not changed between the

Connecting to SQLBase

1-13

Chapter 1

Introduction to SQLBase Connectivity

time it is read and the time it is altered.) There are differences in how isolation levels are mapped between SQLBase and the various drivers and providers - please read the relevant chapters. Cursor Stability (CS)The isolation level where a page acquires a shared lock on it only while it is being read (while the cursor is on it). A shared lock is dropped as the cursor leaves the page, but an exclusive lock (the type of lock used for an update) is retained until the transaction completes. This isolation level provides higher concurrency than Read Repeatability, but consistency is lower. Release Locks (RL)With the Cursor Stability isolation level, when a reader moves off a database page, the shared lock is dropped. However, if a row from the page is still in the message buffer, the page is still locked. In contrast, the Release Lock (RL) isolation level increases concurrency. By the time control returns to the application, all shared locks have been released. Read Only (RO)The isolation level where pages are not locked, and no user has to wait. This gives the user a snapshot view of the database at the instant that the transaction began. Data cannot be updated while in the read-only isolation level. Read Repeatability (RR)The isolation level where if data is read again during a transaction, it is guaranteed that those rows would not have changed. Rows referenced by the program cannot be changed by other programs until the program reaches a commit point. Subsequent queries return a consistent set of results (as though changes to the data were suspended until all the queries finished). Other users will not be able to update any pages that have been read by the transaction. All shared locks and all exclusive locks are retained on a page until the transaction completes. Read repeatability provides maximum protection from other active application programs. This ensures a high level of consistency, but lowers concurrency. RR is the SQLBase default isolation level.

Transactions
SQLBase provides commands COMMIT and ROLLBACK to control transactions. In addition, the SAVEPOINT command can be used within scripts and procedures to create intermediate rollback points within a transaction.

Distributed transactions
In addition to a transaction that is handled on a single database server, SQLBase also provides the ability to do transactions that involve multiple database servers performing various parts of the transaction. For more information about this, read the Distiibuted Transactions chapter in the Database Administrator Guide.

1-14 Connecting to SQLBase

General features of SQLBase

COM+ transactions in Windows


SQLBase for Windows includes SQLBase Resource Manager, a component that makes it possible to coordinate database transactions inside a larger COM+ transaction. For more information, read the Communication chapter of the Database Administrator Guide.

Long character and long binary data handling


The LONG (or LONG VARCHAR) datatype accepts both character and binary data. In Gupta Team Developer, or in applications that use the SQBase native API, there are some extra steps required to make use of this datatype. However, all of the SQLBase drivers and data providers hide this complexity, so you can treate a LONG VARCHAR column just like any other datatype in your SQL commands.

Stored procedures and triggers


SQLBase supports stored procedures. The procedural language is SAL (SQLWindows Application Language), which is the same language used in the SQLWindows tool that is part of Gupta Team Developer. This language is also used in triggers. Parameters are allowed with stored procedures. Parameters can be either input-only or input-output. There is no output-only parameter type. For detailed information and examples of stored procedures and triggers, read the chapter Procedures and Triggers in the SQL Language Reference.

Connecting to SQLBase

1-15

Chapter 1

Introduction to SQLBase Connectivity

1-16 Connecting to SQLBase

Connecting to SQLBase

Chapter 2

ODBC Driver Introduction


This chapter describes SQLBases support for the Microsoft Open DataBase Connectivity (ODBC) standard. The ODBC standard is an application programming interface (API) specification written by Microsoft. It is an effort to standardize the way in which frontend products access database servers from different vendors.

Connecting to SQLBase

2-1

Chapter 2

ODBC Driver Introduction

How does it work?


Each relational database vendor has its own proprietary API. If you want your client application to access a database server, you must code to the database vendors API. Alternatively, you can use a router or gateway product to translate from one vendors API to another vendors API. Guptas SQLRouter products provide such a service. They sit between a Gupta SQLWindows or Report Builder client application and a non-SQLBase database server and translate Gupta API calls into non-SQLBase API calls. Gupta has SQLRouter products that support DB2, DB2/400, Oracle, SQL Server, Sybase, and more. The ODBC standard takes another approach. It calls for all client applications to write to the ODBC standard API and for all database vendors to provide support for it. It then relies on third-party access tools or database drivers (such as the Gupta SQLBase ODBC driver) that conform to the ODBC specification to translate the ODBC standard API calls generated by the client application into the database vendors proprietary API calls.

ODBC overview
The ODBC architecture specifies four components: The application. The application requests a connection with a data source. It calls ODBC functions to submit SQL statements and retrieve results. The Driver Manager. On Windows, the Driver Manager is a dynamic-link library (DLL) that is provided by Microsoft and is included with the Gupta SQLBase ODBC driver. Its primary purpose is to load drivers on behalf of an application. On Linux, a driver manager is a binary component provided by a third party such as iODBC or unixODBC. You must alter the configuration files for these binary components to link them with the SQLBase ODBC driver. The driver. To access SQLBase, you use the Gupta SQLBase ODBC driver, which is packaged with SQLBase. The driver processes ODBC function calls, submits SQL requests to a specific data source, and returns results to the application. If necessary, the driver modifies an applications request so that the request conforms to syntax supported by the associated DBMS. The data source. This consists of the data you want to access and its associated DBMS (in this case, SQLBase), operating system, and network platform (if any).

2-2

Connecting to SQLBase

About the SQLBase ODBC driver for Windows

For more detailed information on ODBC architecture and implementation, read the Microsofts Programmers Reference manual that accompanies the ODBC Software Developers Kit (SDK).

About the SQLBase ODBC driver for Windows


The SQLBase ODBC driver supports the Gupta SQLBase database system in the following operating systems: Windows 98, ME, NT, 2000, Server 2003, and XP. The driver file name is sqlbaseodbc.dll. Driver and data source configuration are done through sqlbaseodbcsetup.dll. The information in this chapter is also available in an online help file that is accessible during ODBC data source configuration.

System requirements
The Gupta SQLBase ODBC driver (SQLBaseODBC.dll) requires: SQLBase version 9.0 or higher. One of the supported operating systems: Microsoft Windows 98, ME, NT, 2000 , XP, or Server 2003. The Microsoft 3.5 Driver Manager. This is included with the Gupta SQLBase ODBC driver.

To communicate with the server, the SQLBase driver requires SQLWNTM.DLL, SQLBAPW.DLL, and a communication DLL (for example, SQLWS32.DLL for TCP/ IP). The directory containing these files must be on your path. Client applications written with a Gupta programming tool, such as SQLWindows, cannot use ODBC to connect to SQLBase. For such applications, use the native SQLBase routers instead.

About the SQLBase ODBC driver for Linux


The SQLBase ODBC driver supports the Gupta SQLBase database system in the following operating systems: Red Hat 9.0, Red Hat Advanced Server 3.0, SUSE 9.0, SUSE Enterprise Server 8.0, SUSE Desktop 1.0. The driver file name is libsqlbaseodbc.so. Driver and data source configuration are done through text editing of configuration files.

System requirements
The Gupta SQLBase ODBC driver (libsqlbaseodbc.so) requires:
Connecting to SQLBase

2-3

Chapter 2

ODBC Driver Introduction

SQLBase version 9.0 or higher. One of the supported operating systems: Red Hat 9.0, Red Hat Advanced Server 3.0, SUSE 9.0, SUSE Enterprise Server 8.0, SUSE Desktop 1.0. A driver manager. The Gupta SQLBase ODBC driver has been tested with the iODBC and the unixODBC driver managers. These are available from third parties.

Note: See release notes for exact versions of operating systems and ODBC driver managers.

Client applications written with Gupta Team Developer cannot use ODBC to connect to SQLBase. For such applications, use the native SQLBase routers instead.

Supported Features
The driver is very similar in its Windows and Linux implementations. Here are the few differences in Linux: The iODBC and unixODBC driver managers do not support Microsoft Distributed Transactions. The SQLBase Linux ODBC Driver supports only non-GUI data source configuration.

ODBC Conformance Level


The API functions supported are listed in Supported ODBC Functions . The driver conforms to ODBC Core and Level 1 completely. In addition, many Level 2 functions and some Level 3 functions are supported. When queried for API conformance, the driver responds that it is Level 2 compliant. The driver supports the SQL Minimum Grammar as well as ODBC Escape Sequences for date, time and timestamp values, outer join and scalar functions.. The driver also supports backward and random fetching in SQLExtendedFetch and SQLFetchScroll.

Number of Connections and Statements Supported


The SQLBase database system supports multiple connections and multiple statements per connection.

Isolation and Lock Levels Supported


SQLBase supports the following standard ODBC isolation levels: SQL_TXN_REPEATABLE_READ (maps to SQLBase level RR), 2-4
Connecting to SQLBase

Supported Features

SQL_TXN_READ_COMMITTED (maps to SQLBase level RL)and SQL_TXN_READ_UNCOMMITTED (maps to SQLBase level RL). SQLBase supports page-level locking.

Supported ODBC Functions


Guptas SQLBase ODBC Driver supports the following functions:
SQLAllocHandle SQLBindCol SQLBindParameter SQLBrowseConnect * SQLCancel SQLCloseCursor SQLColAttribute SQLColumnPrivileges SQLColumns SQLConnect SQLCopyDesc SQLDescribeCol SQLDescribeParam * SQLDisconnect SQLDriverConnect SQLEndTran SQLExecDirect SQLExecute SQLFetch SQLFetchScroll SQLFreeStmt SQLForeignKeys SQLFreeHandle SQLGetConnectAttr SQLGetCursorName SQLGetData SQLGetDescField SQLGetDescRec SQLGetDiagField SQLGetDiagRec SQLGetEnvAttr SQLGetInfo SQLGetStmtAttr SQLGetTypeInfo SQLMoreResults * SQLNativeSql SQLNumParams SQLNumResultCols SQLParamData

Connecting to SQLBase

2-5

Chapter 2

ODBC Driver Introduction

SQLPrepare SQLPrimaryKeys SQLProcedureColumns ** SQLProcedures SQLPutData SQLRowCount SQLSetConnectAttr SQLSetCursorName SQLSetDescField SQLSetDescRec SQLSetEnvAttr SQLSetPos SQLSetStmtAttr SQLSpecialColumns SQLStatistics SQLTablePrivileges SQLTables

* Exported by the driver but currently not fully implemented. Will return standard ODBC error to indicate that it is not implemented. ** Search patterns in SqlProcedureColumns are limited to the % symbol as the last character of the pattern. Any other wildcard characters will return a not-supported error.

Deprecated functions
Below is an alphabetic list of deprecated ODBC API functions. Note that these functions can still be used by an ODBC application, but they are implemented by the ODBC Driver Manager and not by the driver. The driver manager maps these deprecated functions into other functions that are actually implemented by the driver.
Deprecated function SQLAllocConnect SQLAllocEnv SQLAllocStmt SQLBindParam SQLError SQLExtendedFetch SQLFreeConnect Mapped to SQLAllocHandle SQLAllocHandle SQLAllocHandle SQLBindParameter SQLGetDiagRec SQLFetchScroll SQLFreeHandle

2-6

Connecting to SQLBase

Configuring Data Sources in Windows

Deprecated function SQLFreeEnv SQLGetConnectOption SQLGetStmtOption SQLParamOptions SQLSetConnectOption SQLSetParam SQLSetScrollOptions SQLSetStmtOption SQLTransact SQLFreeHandle

Mapped to

SQLGetConnectAttr SQLGetStmtAttr SQLSetStmtAttr SQLSetConnectAttr SQLBindParameter SQLSetStmtAttr SQLSetStmtAttr SQLEndTran

Configuring Data Sources in Windows


To configure a SQLBase data source, do the following: 1. 2. Start the ODBC Administrator to display a list of data sources. If you are configuring an existing data source, select the data source name and click Configure to display the SQLBase Data Source Properties dialog box. If you are configuring a new data source, click Add to display a list of installed drivers. Select Gupta SQLBase and click Finish to display the SQLBase Data Source Properties dialog box. 3. 4. Specify a data source name, a database name and optionally, a description. Click Test Connect to attempt to connect to the data source using the connection properties specified in the Driver Setup dialog box. You may need to supply the name of the database server in the Test Connect dialog box. If desired, configure optional data source settings in the Advanced section of the dialog. Click OK or Cancel. If you click OK, the values you have specified become the defaults when you connect to the data source. You can change these defaults by using this procedure to reconfigure your data source. You can override these defaults by connecting to the data source using a connection string with alternate values. You can also visit the Connection Pooling tab of the ODBC Administrator window to setup up connection pooling for your data source. Connection pooling
Connecting to SQLBase

5. 6.

7.

2-7

Chapter 2

ODBC Driver Introduction

offers performance advantages, and is particularly helpful when your data source is participating in a distributed transaction.

Data Source Properties dialog


Use the ODBC SQLBase Data Source Configuration dialog box to create new SQLBase data sources or configure existing data sources. .

Data Source Name: A string that identifies this SQLBase data source configuration in the system information. Examples include "Accounting" or "SQLBase-Serv1." Description: An optional long description of a data source name. For example, "My Accounting Database" or "SQLBase on Server number 1." Database Name: The name of the database to which you want to connect by default. Isolation Level: The method of locking to use for this connection. Choices are Release Locks, Read Repeatability, Read Only, or Cursor Stability. For detailed information about how these levels work, read the SQLBase Language Reference manual, specifically the SET ISOLATION command.

2-8

Connecting to SQLBase

Configuring Data Sources in Linux

Input Message Size: The number of bytes in the input message buffer. The default is determined by SQLBase. Increasing this value retrieves more records across the network in a single fetch. Lock Timeout: The number of seconds SQLBase should wait for a lock to be freed before raising an error. Values can be -1 (wait forever) to 1800; the default is 300. Config Filename (INI): The name (and, optionally, path) of the configuration file that contains information about SQLBase servers and databases. This name can be left blank; if so, the configuration file is searched for using the algorithm described in chapter 3 of the SQLBase Database Administrators Guide.

Configuring Data Sources in Linux


Driver manager configuration files
Popular ODBC driver managers for Linux, such as iODBC and unixODBC, use configuration files to get data source information. These files are named odbc.ini and odbcinst.ini. They are most commonly found in the /etc directory. Driver managers can also search for configuration files. For example, iODBC searches for odbc.ini as follows: 1. 2. 3. $ODBCINI - Environment variable, if set. ~/.odbc.ini - Located in home-directory ($HOME), if it exists for user DSN /etc/odbc.ini - A system-wide default

Changing configuration information


Configuration changes are done by using a text editor on the configuration files. In the case of unixODBC it is possible to use a utlility, odbcinst, to make changes to the configuration files. However, you would still use a text editor to enter the lines that are shown in the examples below into a template file, then use odbcinst to actually copy those lines from the template file into the configuration files. For more detail about using odbcinst instead of editing the configuration files manually, see Nick Gorhams explanation of odbcinst. Shown below is an example data source, "Gupta1", as it would be configured for different driver managers.

unixODBC
To learn how unixODBC searches for its configuration files, see the unixODBC web site. Entries in the odbcinst.ini file:

Connecting to SQLBase

2-9

Chapter 2

ODBC Driver Introduction

[Gupta SQLBase] Driver = /opt/Gupta/SQLBase90/libsqlbaseodbc.so Setup = /opt/Gupta/SQLBase90/libsqlbaseodbcsetup.so

Here are the corresponding entries in the odbc.ini file:


[gupta1] Driver=/opt/Gupta/SQLBase90/libsqlbaseodbc.so Description=Gupta SQLBase DSN DSN=gupta1 Servername=server1 LoginID=SYSADM Username=SYSADM Password=SYSADM Database=island ini=/opt/Gupta/SQLBase90/sql.ini InputMessageSize=2000 IsoLevel=Release Locks LockTimeOut=300

iODBC
The configuration entries for iODBC are similar, but not identical, to unixODBC. Here is the odbcinst.ini file:
;------ /etc/odbcinst.ini file begin ----; ; odbcinst.ini ; [ODBC Drivers] Gupta SQLBase = Installed [Gupta SQLBase] Driver = /opt/Gupta/SQLBase90/libsqlbaseodbc.so Setup = /opt/Gupta/SQLBase90/libsqlbaseodbcsetup.so

And here is the odbc.ini file:


;------ /etc/odbc.ini file begin ----; ; odbc.ini ; [ODBC Data Sources] Gupta1=Gupta SQLBase ODBC Driver [Gupta1] Description=Gupta SQLBase DSN Driver=/opt/Gupta/SQLBase90/libsqlbaseodbc.so DSN=gupta1

2-10 Connecting to SQLBase

How-to information for ODBC

Servername=server1 LoginID=SYSADM Username=SYSADM Password=SYSADM Database=island ini=/opt/Gupta/SQLBase90/sql.ini InputMessageSize=2000 IsoLevel=Release Locks LockTimeOut=300 [Default] Driver = /opt/Gupta/SQLBase90/libsqlbaseodbc.so ;------ /etc/odbc.ini file end -----

How-to information for ODBC


How do SQLBase datatypes map to ODBC datatypes?
The SQLBase data types are mapped to the standard ODBC data types as follows:
SQLBase Char Date Decimal Double Precision Integer Long Varchar Number Real Smallint Time Timestamp Varchar SQL_VARCHAR SQL_TYPE_DATE SQL_DECIMAL SQL_DOUBLE SQL_INTEGER SQL_LONGVARCHAR SQL_DOUBLE SQL_REAL SQL_SMALLINT SQL_TYPE_TIME SQL_TYPE_TIMESTAMP SQL_VARCHAR ODBC

Connecting to SQLBase

2-11

Chapter 2

ODBC Driver Introduction

How do I start a transaction?


By turning off autocommit, your application begins an implicit transaction.
SQLSetConnectAttr(hdbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF);

You can end the transaction with either a rollback or commit flag.
SQLEndTran(henv, hdbc, SQL_COMMIT);

Distributed transactions benefit from connection pooling. For more information about configuring connection pooling, see Configuring Data Sources in Windows on page 2-7. For information about changing connection pooling from within an application, search the Microsoft KnowledgeBase using connection pooling to find information on code samples.

How do I set isolation levels?


To set isolation level, use the connection property SQL_TXN_ISOLATION. Set it to one of the supported levels, as listed in Isolation and Lock Levels Supported on page 2-4

How do I read and write long character and long binary data?
ODBC functions SqlGetData and SqlPutData are the primary methods of handling the ODBC datatype SQL_LONGVARCHAR., which can contain either long character or long binary information. In this fragment of C code, a large text string is first written to the database, then read back from the database.
rc = SQLExecDirect(hstmt, "DROP TABLE TBLOB", SQL_NTS); rc = SQLTransact(henv, hdbc, SQL_COMMIT); rc = SQLExecDirect(hstmt, "CREATE TABLE TBLOB (I INTEGER NOT NULL , B LONG )", SQL_NTS); assert(rc == SQL_SUCCESS); rc = SQLTransact(henv, hdbc, SQL_COMMIT); assert(rc == SQL_SUCCESS); cbValue = 0; rc = SQLPrepare(hstmt, "INSERT INTO TBLOB VALUES (?, ?)", SQL_NTS); assert(rc == SQL_SUCCESS); rc = SQLSetParam(hstmt, 1, SQL_C_LONG, SQL_INTEGER, 0, 0, &l, NULL); assert(rc == SQL_SUCCESS);

2-12 Connecting to SQLBase

How-to information for ODBC

rc = SQLSetParam(hstmt, 2, SQL_C_CHAR, SQL_LONGVARCHAR, blob_size, 0, NULL, &cbValue); assert(rc == SQL_SUCCESS); cbValue = SQL_DATA_AT_EXEC; l = 2; blobbuf = malloc(blobbuf_size); memset(blobbuf, 'A', blobbuf_size); rc = SQLExecute(hstmt); assert(rc == SQL_NEED_DATA); rc = SQLParamData(hstmt, &token); if (rc == SQL_NEED_DATA) { for (j = 0; j < blob_size; ) { SDWORD s; s = (SDWORD)blobbuf_size; if (s + j > blob_size) { s -= (s + j) - blob_size; assert(s + j != blob_size); } rc = SQLPutData(hstmt, blobbuf, s); assert(rc==SQL_SUCCESS); j += (ULONG)s; } rc = SQLParamData(hstmt, &token); assert(rc == SQL_SUCCESS); } else { error_line(__LINE__); } rc = SQLTransact(henv, hdbc, SQL_COMMIT); assert(rc == SQL_SUCCESS); rc = SQLFreeStmt(hstmt, SQL_RESET_PARAMS); assert(rc == SQL_SUCCESS);

memset(blobbuf, ~0, 100); rc = SQLPrepare(hstmt, "SELECT I, B FROM TBLOB WHERE I = 2", SQL_NTS); assert(rc == SQL_SUCCESS); rc = SQLExecute(hstmt); assert(rc == SQL_SUCCESS); rc = SQLFetch(hstmt); assert(rc == SQL_SUCCESS); rc = SQLGetData(hstmt, 1, SQL_C_LONG, &l, 0L, &cbValue);

Connecting to SQLBase

2-13

Chapter 2

ODBC Driver Introduction

assert(rc == SQL_SUCCESS); blob_read = 0L; do { rc = SQLGetData(hstmt, 2, SQL_C_BINARY, blobbuf, blobbuf_size, &cbValue); assert(cbValue > 0); blob_read += (cbValue < blobbuf_size ? cbValue : blobbuf_size); } while (rc == SQL_SUCCESS_WITH_INFO); assert(rc == SQL_SUCCESS); assert(blob_read == blob_size); rc = SQLFreeStmt(hstmt, SQL_CLOSE); assert(rc == SQL_SUCCESS); free(blobbuf); }

How do I run stored procedures?


A stored procedure without parameters can be run like a regular SQL query, as in this C example:
sql= "{call maketables}"; rc = SQLExecDirect(hstmt,sql,SQL_NTS); CHECK(rc,hstmt);

A stored procedure that uses parameters requires the use of binds, as in this example of procedure "test" that was created with a string parameter named "quote":
/* Prepare the procedure invocation statement */ SQLPrepare(hstmt, "{call test(?)}", SQL_NTS); /* Populate record 1 of IPD */ SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 30, 0, szQuote, 0, &cbValue); /* Get IPD handle and set the NAMED and UNNAMED fields for record # 1 */ SQLGetStmtAttr(hstmt, SQL_ATTR_IMP_PARAM_DESC, &hIpd, 0, 0); SQLSetDescField(hIpd, 1, SQL_DESC_NAME, "quote", SQL_NTS); /* Assuming that szQuote has been appropriately initialized, execute the statement */ SQLExecute(hstmt);

2-14 Connecting to SQLBase

Connecting to SQLBase

Chapter 3

Making an ODBC Connection


Connection strings
If your application requires a connection string to connect to a data source, you must specify the data source name that tells the driver which section of the odbc.ini file to use for the default connection information. Optionally, you may specify attribute or value pairs in the connection string to override the default values stored in the odbc.ini file. You can specify either long or short attribute names in the connection string. Gupta recommends that you use long names. The connection string has the following format: DSN=data source name[;attribute=value[;attribute=value]...] An example of a connection string for SQLBase is:
DSN=SQLBase Island;SERVER=SERVER1;DATABASE=PAYROLL; UID=JOHN;PWD=XYZZY

Connection string keywords


Driver: Used in DSN-less connections, and is required to tell the Driver Manager which ODBC driver the rest of the connection string pertains to.

Connecting to SQLBase

3-1

Chapter 3

Making an ODBC Connection

DataSourceName (DSN): A string that identifies a single connection to a SQLBase database system, for example, "Accounting". Database (DB): The name of the database system to which you want to connect. ServerName (SRVR): The name of the server that hosts the database to which you want to connect. LogonID (UID): The default Logon ID used to connect to your SQLBase system. A Logon ID is required only if security is enabled on your database system. If so, contact your system administrator to get your Logon ID. This value is case-sensitive. Password (PWD): Case-sensitive password. IsoLevel (IL): A string that specifies how SQLBase will handle locking for this connection. Possible values are RL (Release Locks), RR (Read Repeatability), RO (Read-Only), and CS (Cursor Stability). For detailed information about how these levels work, read the SQLBase Language Reference manual, specifically the SET ISOLATION command. InputMessageSize (IMS): Controls the number of bytes of the input message buffer. Increasing this value retrieves more records across the network in a single fetch. LockTimeOut (LTO): Number of seconds SQLBase waits for a lock to be freed before raising an error. Values can be -1 to 1800. A value of -1 is infinite wait. Default is 300. NoRecovery (NR): This keyword is accepted for backwards compatibility, but has no effect on the SQLBase server.

Logon dialog
Your application might supply enough information in the connection string to make the connection without prompting you. If not, when the SQLBase ODBC Driver needs additional information from you to make a connection, it displays a dialog box. Fill out the values in the dialog box as shown below:
Note: The logon dialog is available only in the Windows ODBC driver, not in the Linux ODBC driver. In the Linux ODBC driver, if the connection string contains insufficient information to make a connection, the database server will return an error.

3-2

Connecting to SQLBase

Linux connections

1.

Optionally, type the name of the server containing the SQLBase database tables you want to access or select the name from the Server Name drop-down list box, which displays the server names you specified in the Setup dialog box. Type Local to access a local SQLBase database. Type the name of the database you want to access. If you specified a server name, you can select the name from the Database Name drop-down list box. If required, type your user name. If required, type your password.

2. 3. 4.

Click OK to complete the logon and to update the values in the system information.

Linux connections
Since there is no logon dialog for Linux operating systems, your Linux ODBC configuration files must be complete and accurate before you attempt to log on. The data source that you wish to connect to must be present in these files (particularly odbc.ini.). Several lines are necessary for each data source. See the sample "Gupta1" data source, as it is configured in unixODBC on page 2-9 or iODBC on page 2-10.

PHP example
An example of how a PHP script might connect to the Gupta1 data source from chapter 2 is shown below. The following script effects a connection to a database (`Gupta1' is the default DSN), and either executes a query or lists tables present in that database. Save this code to a file php-odbc-sample.php.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:/ /www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Connecting to SQLBase

3-3

Chapter 3

Making an ODBC Connection

<html> <head> <title> Gupta test of ODBC access through PHP hosting</title> <link type="text/css" rel="STYLESHEET" media="ALL" href="../../tutorial.css" /> </head> <body> <h1>Testing ODBC connectivity from PHP hosted within Gupta</h1> <hr /> <?php # set global variables based on the form thing - see `register global # variables' and PHP security updates $query=$_POST['query']; $uid=$_POST['uid']; $passwd=$_POST['passwd']; $listtables=$_POST['listtables']; $DSN=$_POST['DSN']; $exec=$_POST['exec']; ?> <p>Enter the parameters for your query here:</p> <form action="php-odbc-sample.php" method="post"> <div> <span class="caption">DSN</span> <input type="text" name="DSN" value="<?php print ($DSN<>"")?$DSN:"Gupta1" ?>" /> <span class="caption">UserID</span> <input type="text" name="uid" value="<?php print ($uid<>"")?$uid:"sysadm" ?>" /> <span class="caption">Password</span> <input type="password" name="passwd" value="<?php print ($passwd<>"")?$passwd:"sysadm"?>" /> </div> <div> <span class="caption">Query</span> <input type="text" name="query" value="<?php print ($query<>"")?$query:"select * from budget"

3-4

Connecting to SQLBase

Linux connections

?>" /> </div> <div> <input type="submit" name="exec" value="Execute query" /> or <input type="submit" name="listtables" value="List Tables" /> </div> </form> <hr /> <?php if($query<>"" && $DSN<>"" && $exec!=NULL) { print "<h2>Results:</h2> "; print "<p>Connecting... "; $handle=odbc_connect ("$DSN", "$uid", "$passwd"); if(!$handle) { print "<p>Uh-oh! Failure to connect to DSN [$DSN]: <br />"; odbc_errormsg(); } else { print "done</p> "; $resultset=odbc_exec ($handle, "$query"); odbc_result_all($resultset, "border=2"); odbc_close($handle); } } if($listtables!=NULL) { print "<h2>List of tables</h2>"; print "<p>Connecting... "; $handle=odbc_connect ("$DSN", "$uid", "$passwd"); print "done</p> "; if(!$handle) { print "<p>Uh-oh! Failure to connect to DSN [$DSN]: <br />"; odbc_errormsg(); } else { $resultset=odbc_tables($handle); odbc_result_all($resultset, "border=2"); odbc_close($handle);

Connecting to SQLBase

3-5

Chapter 3

Making an ODBC Connection

} } ?> </body> </html>

3-6

Connecting to SQLBase

Connecting to SQLBase

Chapter 4

Introducing SQLBase OLE DB Data Provider


This chapter contains an overview of SQLBase OLE DB Data Provider functionality and software requirements. It also discusses ActiveX Data Objects (ADO) and how the SQLBase OLE DB Data Provider works with the ADO standard.

Connecting to SQLBase

4-1

Chapter 4

Introducing SQLBase OLE DB Data Provider

Overview
OLE DB is an application programming interface, written by Microsoft. Part of Microsofts Universal Data Access strategy, it aims to facilitate access to information across data sources. The goal is to reliably offer high-performance data access that supports industry standards. The Universal Data Access strategy addresses the technical obstacles organizations face when trying to disseminate information across client/server networks and the World Wide Web. This task becomes more of a challenge given multiple platforms, legacy systems, and numerous programming languages and development tools. Based on open industry specifications, Universal Data Access allows developers to extend the capabilities of existing technologies. OLE DB fits into this strategy by giving developers the ability to write applications that have uniform access to data regardless of the data source and development tool. Using OLE DB, it is possible for different pieces of an application to be written in different languages due to OLE DBs COM structure.

OLE DB components
The two main components of OLE DB are a data provider and a data consumer. An OLE DB data provider responds to OLE DB calls resulting in data being returned in a usable tabular format. A data consumer is an application or COM component that uses the OLE DB API to access a data source. Since OLE DB comprises a set of Component Object Model (COM) interfaces, it results in a high level of interoperability among programming tools. The COM interfaces support the full DBMS functionality of the data source. The COM specification allows you to use a variety of programming tools, such as Visual Basic and Delphi, to develop application components that can function within a single application.

Recommended reading
To make the best use of OLE DB, we recommend that you read Microsoft OLE DB 2.0 Programming Reference and Data Access SDK.

About SQLBase OLE DB Data Provider


Built upon OLE DB technology, SQLBase OLE DB Data Provider lets programmers access SQLBase functionality from a variety of supported visual programming tools. Historically, developers have had to call SQL/API functions or use the ODBC API to access a database. SQLBase OLE DB Data Provider exposes SQLBase Server properties more completely than the ODBC driver does, allowing developers to directly interface with the database and server using a variety of programming tools. SQLBase OLE DB Data Provider is a set of COM objects that expose the SQLBase functionality needed by developers to build applications. In addition to standard OLE 4-2
Connecting to SQLBase

About SQLBase OLE DB Data Provider

DB conformance, the Provider interfaces enable access to DBMS functionality not normally provided by OLE DB, including backup, create database, and shutdown server. A DLL, SQLBase OLE DB Data Provider runs in the address-space of the client program and is written over the SQL/API. Using OLE DB interfaces, the Provider lets you define DBMS components, including row containers, query processors, and transaction coordinators. Another level of simplification: ADO. The Provider also provides high level access to your data through ActiveX Data Objects (ADO). The following figure shows the role of SQLBase OLE DB Data Provider in the application development process. Application

ADO
SQLBase OLE DB Data Provider Other Data Providers

SQL/API

ODBC

Other databases SQLBase databases Other data sources

Connecting to SQLBase

4-3

Chapter 4

Introducing SQLBase OLE DB Data Provider

SQLBase OLE DB Data Provider name


When you configure a programming tool to use the Provider, you may need to enter a provider name. For SQLBase OLE DB Data Provider, the name is: SQLBaseOLEDB The provider string is initialized for the open call that establishes a connection to SQLBase through the OLE DB provider. The name of the SQLBase OLE DB provider is hard-coded as a constant. The user ID, password, location and data source (tablename) are read from objects in your code. Here is a sample:
Dim sConnect As String ' holds ADO connect string ' set up connection string and open connection to data source sConnect = "Provider=SQLBASEOLEDB" _ & ";Data Source=ISLAND" _ & ";User ID=SYSADM" _ & ";Password=sysadm"

For a more complete example of connecting to SQLBase using ADO, read Chapter 5, Establishing a connection using ADO.

Data source name


Some programming tools may prompt you for a data source name. For SQLBase OLE DB, the data source name is the name of the SQLBase database itself (for example, ISLAND).

Supported programming tools


SQLBase OLE DB Data Provider is designed to work with the following programming tools: Gupta Team Developer (SQLWindows), all the languages of Microsofts Visual Studio, Delphi, Crystal Reports, PowerBuilder, and many others. In general, SQLBase OLE DB Data Provider works with any development environment that supports OLE DB data access.

How-to information for the OLE DB provider


How do SQLBase datatypes map to OLE DB datatypes? How do I start a transaction?
Through the ITransactionLocal::StartTransaction and ITransactionJoin::JoinTransaction methods of the Session object, your application can initiate local transactions and/or join in distributed transactions. 4-4
Connecting to SQLBase

How-to information for the OLE DB provider

SQLBase support for these interfaces is identical to the support described in the Microsoft Developer Network documentation. In MSDN, search for those method or interface names to get more detail on the overall transaction process.

How do I set isolation levels?


The first parameter of the ITransactionLocal::StartTransaction method is isolation level. Use one of the supported levels shown in Isolation level mapping on page 6-2. Note that not all OLE DB isolation levels are supported by SQLBase.

How do I use long character data and long binary data?


These are edited code frargments from sample project Tut5, in Visual Basic version 6. They illustrate how to fetch long data into an image. Populate a Recordset from a query that includes a SQLBase LONG VARCHAR datatype:
strSQL = "SELECT EMPLOYEE_ID, LAST_NAME, FIRST_NAME, EMAIL, CURRENT_SALARY, PHOTO1 FROM EMPLOYEE" Dim myRS As ADODB.Recordset Dim iCount As Integer myADO.setCursorType (adOpenKeyset) myADO.setLockType (adLockOptimistic) myADO.doSelect (strSQL) Set myRS = myADO.getRS If Not myRS.BOF And Not myRS.EOF Then myRS.MoveFirst End If

Get the value of a Recordset column and convert it to a byte array, then a file, then load the image with the file.
Dim chunk() As Byte chunk() = StrConv(myRS("PHOTO1").Value, vbFromUnicode) Set strStream = New ADODB.Stream strStream.Type = adTypeBinary strStream.Open strStream.Write chunk strStream.SaveToFile "C:\Temp.gif", adSaveCreateOverWrite Image1.Picture = LoadPicture("C:\Temp.gif")

Connecting to SQLBase

4-5

Chapter 4

Introducing SQLBase OLE DB Data Provider

Writing long binary information to the database can be accomplished by changing the value of a Recordset column. In this case the binary information was first written to a file.
Set strStream = New ADODB.Stream strStream.Type = adTypeBinary strStream.Open strStream.LoadFromFile sFileName strStream.Position = 0 strStream.Type = adTypeText strStream.Charset = "ISO-8859-1" myRS.Fields("PHOTO1").Value = strStream.ReadText myRS.Save

When working with long character data, you can choose to move it to a Byte array. You can also simply fetch it into the Text value of a TextBox or RichTextBox control, or into a string variable.

ADO Overview
Microsoft ActiveX Data Objects (ADO) enables you to write an application to access and manipulate data in a database server through an OLE DB provider, such as the SQLBase provider. ADO's primary benefits are data source independence, high speed, ease of use, low memory overhead, and a small disk footprint. Since ADO is independent of the data source, you do not have to know all the intricacies of the database to take advantage of the provider. For more general information about OLE DB providers, see the documentation for the Microsoft OLE DB SDK or visit the Microsoft OLE DB Web page. The SQLBase OLE DB Data Provider is a standard provider you can use with ADO as you would other standard providers. To make the best use of ADO, we recommend you access the samples in: www.microsoft.com/data and access further information on ADO in: www.microsoft.com/data/ado

ADO features
ADO provides a number of features for building client/server and Web-based applications. Using the SQLBase provider with ADO, you can take advantage of:

4-6

Connecting to SQLBase

ADO Overview

Independently-created objects. Unlike Data Access Objects (DAO) or Remote Data Objects (RDO), you no longer have to navigate through a hierarchy to create objects because most ADO objects can be independently created. This allows you to create and track only the objects you need, and also results in fewer ADO objects and thus a smaller working set. Batch updating. If you are using client-side cursors, you can do batch updating. This helps improve performance by locally caching changes to data, then writing them all to the server in a single update. Support for stored procedures with input (not output) parameters. Different cursor types, including support of backendspecific cursors. With the SQLBase provider, when the user asks for the ability to fetch backward or scroll backward, the provider asks the server to enable its cursors.

Remote Data Service


ADO's Remote Data Service (RDS) allows data remoting, by which you can move data from a server to a client application or Web page, manipulate the data on the client, and return updates to the server in a single round trip. Previously released as Advanced Data Connector, RDS has been combined with the ADO programming model to simplify client-side data remoting. For more information, see the Remote Data Service documentation. As part of the Microsoft Data Access Components, ADO and RDS are automatically installed and registered by a host product, such as Microsoft Internet Information Server. The host product setup program may require that you specifically request the Microsoft Data Access Components in order to have ADO and RDS installed.

Programming with ADO


ADO is a dual-interface COM type library. The file name is msado15.dll. The program ID (ProgID) is "ADODB." In two- and three-tier database applications, ADO code that is to execute on the client uses the ProgID "ADOR" instead. To use ADO with Microsoft Visual Basic or Microsoft Office, you also need to establish a reference to the ADO type library. From the Project menu, select References, check the box for "Microsoft ActiveX Data Objects 1.5 Library," and then click OK. ADO objects, methods, and properties will then be accessible through the VBA Object Browser and the IDE Editor. To use ADO with Microsoft Visual J++, you also need to create a set of class files using the Java Type Library Wizard. From the Tools menu, select the Java Type Library Wizard, check the box for "Microsoft ActiveX Data Objects 1.5 Library," and then click OK. The wizard will then create the necessary Java class files for ADO.

Connecting to SQLBase

4-7

Chapter 4

Introducing SQLBase OLE DB Data Provider

For some programming languages, you also need to reference (using the #include statement) one or more additional files in your source code, as shown here:
C++ adoint.h adoid.h VBScript adovbs.inc JScript adojavas.inc

Threading
With SQLBase OLE DB Data Provider, use ADO as apartment-model threaded.

ADO Objects
Although you create ADO objects outside the scope of a hierarchy, the objects exist within hierarchical relationships, as shown in the ADO Object Model. There are seven objects in the ADO object model: Command Maintains information about a command, such as a query string, parameter definitions, and so on. You can execute a command string on a Connection object or a query string as part of opening a Recordset object, without defining a Command object. The Command object is useful where you want to define query parameters, or execute a stored procedure that returns output parameters. Connection Maintains connection information with the data provider. Error Contains extended error information about an error condition raised by the provider. Because a single statement can generate two or more errors, the Errors collection can contain more than one Error object at a time, all of which result from the same incident. Field Contains information about a single column of data within a Recordset. The Recordset object features a Fields collection to contain all of its Field objects. Parameter A single parameter for a parameterized Command. The Command object features a Parameters collection to contain all of its Parameter objects. Property A provider-defined characteristic of an ADO object. Recordset A set of records returned from a query, and a cursor into those records. You can open a Recordset (that is, execute a query) without explicitly opening a Connection object. However, if you do first create a Connection object, you can open multiple Recordset objects on the same connection. Cursor In ADO, this is the equivalent of a recordset. Each of these objects features a set of properties and methods with which you can manipulate the object and its contents. 4-8
Connecting to SQLBase

ADO Overview

Dynamic Properties Collections


The Connection, Command, and Recordset objects each support a Properties collection. The properties collection contains any dynamic (or "provider-specific") properties exposed through ADO by the SQLBase provider. You use the collection and the Item method to reference the property by its name or by its ordinal position in the collection, as shown: Command.Properties.Item(0) Command.Properties.Item("Name") Because the Item method is a default method on an ADO collection, you can omit it: Command.Properties(0) Command.Properties("Name") Further, the Properties collection itself is the default collection for the Connection, Command, and Recordset objects, so you can omit it as well: Command(0) Command("Name") All of these syntax forms are identical. Which one you choose depends on your coding style preference.

Working with Data


In ADO, the Recordset object is the main interface to data. While the other objects are useful for managing connections, collecting error information, persisting queries, and so on, most of your code's interaction with ADO will involve one or more Recordset objects. This Microsoft Visual Basic Scripting code generates a Recordset from a SQLBase data source:
set rstMain = CreateObject("ADODB.Recordset") rstMain.Open "SELECT * FROM company", _ "provider=SQLBaseOLEDB;Data source=ISLAND"

The first line creates the ADO Recordset object. The second line opens the recordset with a query. The third line specifies the SQLBase provider and the data source. This generates a forward-only, read-only Recordset object. With a few modifications, you can obtain a more functional Recordset:
set rstMain = CreateObject("ADODB.Recordset") rstMain.Open "SELECT * FROM company", _

Connecting to SQLBase

4-9

Chapter 4

Introducing SQLBase OLE DB Data Provider

"provider=SQLBASEOLEDB;Data source=ISLAND", adOpenKeyset, adLockBatchOptimistic

This creates a fully scrollable and batch-updatable Recordset. In order to reference ADO constants by name (instead of by value) when coding in a scripting language, as shown in these code examples, you must include the appropriate header file. For Microsoft Visual Basic Scripting code, include the file adovbs.inc in your code. For Microsoft JScript, include the file adojavas.inc in your code. You should always refer to constants by name rather than by value because the values may change from one version to the next. However, because each provider is unique, how your application interacts with ADO will vary slightly between different providers. The differences you need to be aware of when using SQLBase OLE DB Data Provider are: Connection parameters in the ConnectionString property. Command object usage. Recordset behavior.
Note: For the Recordset object, Gupta recommends that you use server-side cursors (adUseServer). If client cursors are used, then at the end of your applications unit of work, all the changes should be committed using the UpdateBatch() method. UpdateBatch() throws up following warning message which can be ignored: Run-time error '-2147217864 (80040e38)': Row cannot be located for updating. Some values may have been changed since it was last read

SQLBase provider-specific dynamic properties


The Properties collections of the Connection, Command, and Recordset objects include dynamic properties specific to the SQLBase provider. These properties provide information about functionality beyond the built-in properties ADO supports. After establishing the connection and creating these objects, use the Refresh method on the object's Properties collection to obtain the SQLBase provider-specific properties.

Sample applications
The SQLBase provider comes with a number of sample applications. These samples have been developed to show some of the ways ADO can be used with Visual BASIC to communicate with the SQLBase database product. simplefetch Lets you connect to SQLBase and navigate, forward and backwards, through the COMPANY table - part of the ISLAND sample database for SQLBase. The code for this application is discussed in detail later in this chapter. 4-10 Connecting to SQLBase

Connecting to data through the Provider

schema Lets you query the ADO schema types that the SQLBase OLE DB Data Provider supports.

DBExplore Lets you query SQLBase using SQL statements to return Recordsets from the SQLBase database. DBExplore.exe pulls out a Long Binary set of information, processes it, and writes it out to a file. Long text fields and Long Binaries are treated the same by the provider.

SqlBaseNativeCmdSample Demonstrates the SQLBase Native commands (load, unload, store, erase and retrieve) .

You must have installed Microsoft Visual Basic 6.0, the Microsoft Data Access components and the SQLBase OLE DB Data Provider in order to use these samples.

Connecting to data through the Provider


Whether or not you use ADO or direct OLE DB, you acquire database information using these steps: 1. 2. 3. 4. 5. 6. Initialize the provider. Establish a connection. Open a recordset object. Navigate through the database. Process the recordset. Disconnect.

Establishing a connection using ADO


ADO is an OLE DB consumer; it consumes OLE DB interfaces and data from the provider. To establish a connection to SQLBase through ADO, the sample we present in the next section follows these steps: 1. Create the various ADO objects. For example, a connection object, a recordset object, and an error object. 2. 3. 4. Define a routine to output the Errors collection. Define a routine to safety handle null fields. Define a routine to fetch the values of the various fields from the database table.
Connecting to SQLBase

4-11

Chapter 4

Introducing SQLBase OLE DB Data Provider

Our sample assigns the field data to text boxes on the Visual BASIC form. 5. Define the code for the Connect button. The name of the SQLBase OLE DB provider is SQLBaseOLEDB. This is hardcoded as a constant. The user, password, and data source (tablename) are read from TextBox objects. 6. 7. 8. 9. Provide code for a button for closing the connection to SQLBase. Provide code for a button that moves to the first record in the returned Recordset. Provide code for a button that moves to the next record in the RecordSet. Provide code for a button that moves to the previous record in the RecordSet.

10. Provide code for button that moves to the last record in the RecordSet.

Coding Sample using ADO


The following code sample illustrates how to use SQLBase OLE DB Data Provider. For more information, refer to the samples that ship with the product. The code fragments show how to establish a connection, open a recordset object, and navigate through a SQLBase table using ADO in Visual BASIC. They are based on the simplefetch sample supplied with the OLE DB Provider. Portions of the code that don't specifically illustrate the concepts used have been excluded from this text for brevity. 1. Create the various ADO objects

Dim cnCompany As New ADODB.Connection Dim rsCompany As New ADODB.Recordset Dim erCompany As ADODB.Errors

2.

Define two routines to output the Errors collection. OutputErrorMessages() is called whenever an error condition is signalled from the provider. This routine outputs the elements of the Errors collection, one at a time, by calling OutputMessage(). OutputMessage adds the messages to a ListBox on the form, and keeps the latest message in view at all times.

Private Sub OutputErrorMessages() loop through errors returned from provider, output to Messages Listbox Dim ErrLoop As Error Set erCompany = cnCompany.Errors For Each ErrLoop In erCompany

4-12 Connecting to SQLBase

Establishing a connection using ADO

OutputMessage ("Error: " _ & Str(ErrLoop.NativeError) & " " _ & ErrLoop.SQLState _ & ErrLoop.Description) Next ErrLoop End Sub Private Sub OutputMessage(sMessage As String) lbMessages.AddItem (sMessage) lbMessages.TopIndex = lbMessages.ListCount - 1 End Sub

3.

Define a routine to check for null fields. TextBox objects can be bound to your recordset object, to cause them to update and handle NULL values automatically. Because this sample obtains the values directly, IsNull is called on each value to prevent errors from Visual BASIC when returning NULL values.

Private Function GetField(sFieldName As String) As String If Not IsNull(rsCompany.Fields(sFieldName)) Then GetField = rsCompany.Fields(sFieldName) Else GetField = "" End If End Function

4.

Define a routine to fetch the values of the various fields from the database table, assigning them to TextBox objects on the form. A check for BOF or EOF prevents errors when attempting to display values outside the table. GetField() is used to prevent issues with NULL values returned from the provider.

Private Sub UpdateFieldsDisplay() If Not rsCompany.BOF And Not rsCompany.EOF Then ' fill fields of form from DB table CompanyID = GetField("Company_ID") CompanyName = GetField("Company_Name") Address = GetField("Address") City = GetField("City") State = GetField("State") End If End Sub

Connecting to SQLBase

4-13

Chapter 4

Introducing SQLBase OLE DB Data Provider

5.

Define the code for the Connect button. This is where the connection to the database is established, and the recordset object is connected to the COMPANY table.

Private Sub pbConnect_Click()

Establish error trapping, and clear the Errors collection to set up for the open attempt.
On Error GoTo FindErr cnCompany.Errors.Clear ' clear errors list

The provider string is initialized for the open call that establishes a connection to SQLBase through the OLE DB provider. The name of the SQLBase OLE DB provider is hard-coded as a constant. The user, password, and data source (tablename) are read from TextBox objects on the form.
Dim sConnect As String ' holds ADO connect string

' set up connection string and open connection to data source sConnect = "Provider=SQLBaseOLEDB" _ & ";Data Source=" & ebDataSourceName.Text _ & ";User ID=" & ebUserID.Text _ & ";Password=" & ebPassword.Text

Note that instead of providing an explicit connection string as shown above, you can also place the name of a UDL file (must have extension .udl) into the string. The Open function will then read that file and use the contents as the connection string. So the second way of initializing sConnect is as follows:
sConnect = "c:\\My Documents\\my_config.udl"

Then do the actual connection...


cnCompany.Open sConnect

Connect the RecordSet object to the COMPANY table. The adOpenDynamic parameter is used to allow backward navigation through the table in this sample.
' open recordset on COMPANY table rsCompany.Open "COMPANY", cnCompany, adOpenDynamic, , adCmdTable

4-14 Connecting to SQLBase

Establishing a connection using ADO

Move the RecordSet object to the first record in the table, and call the routine to display the field values on the form.
' move to first record, update display of fields rsCompany.MoveFirst Call UpdateFieldsDisplay Exit Sub

Provide an error routine that reports any problems with the connection to SQLBase or the COMPANY table.
FindErr: ' error occurred -- loop through error list and add messages to listbox Call OutputErrorMessages ' clear errors queue, restore arrow cursor, exit subroutine cnCompany.Errors.Clear Exit Sub End Sub

6.

Provide code for a button for closing the connection to SQLBase.

Private Sub pbDisconnect_Click() cnCompany.Close End Sub

7.

Provide code for a button that moves to the first record. We must call UpdateFieldsDisplay() to update the fields on each movement of the RecordSet object.

Private Sub pbFirst_Click() ' move to first record, update fields display rsCompany.MoveFirst Call UpdateFieldsDisplay End Sub

8.

Provide code for a button that moves to the next record in the RecordSet. Special checks are made to stop at the end of the table.

Private Sub pbNext_Click() ' if we're not past last record, move to next record

Connecting to SQLBase

4-15

Chapter 4

Introducing SQLBase OLE DB Data Provider

If Not rsCompany.EOF Then rsCompany.MoveNext ' if we're NOW past the last record... If rsCompany.EOF Then ' put cursor back on last record rsCompany.MoveLast Else Call UpdateFieldsDisplay End If End Sub

9.

Provide code for button that moves to the previous record in the RecordSet. Checks are made to stop at the beginning of the table.

Private Sub pbPrev_Click() ' if we're not before the first record, move to previous record If Not rsCompany.BOF Then rsCompany.MovePrevious ' if we're NOW before the first record... If rsCompany.BOF Then ' put cursor back on first record rsCompany.MoveFirst Else Call UpdateFieldsDisplay End If End Sub

10. Provide code for button that moves to the last record in the RecordSet.
Private Sub pbLast_Click() ' move to last record, update fields display rsCompany.MoveLast Call UpdateFieldsDisplay End Sub

4-16 Connecting to SQLBase

Connecting to SQLBase

Chapter 5

Supported OLE DB COM Objects


This chapter describes the OLE DB COM objects supported by SQLBase OLE DB Data Provider. In this chapter, the tables describe interfaces of objects the Provider supports, and whether our support is standard or specific.

Connecting to SQLBase

5-1

Chapter 5

Supported OLE DB COM Objects

Supported COM objects


SQLBase OLE DB Data Provider uses OLE DB COM objects and their supported interfaces to provide access to SQLBase functionality. SQLBase OLE DB Data Provider uses the following COM cotypes: Data Source (TDataSource) objects contain the machinery to connect to a data source, such as a file or a DBMS. These objects function as factory for sessions. Session (TSession) objects create a context for transactions and can be implicitly or explicitly transacted. A single data source object can create multiple sessions. Sessions are a factory for transactions, commands, and rowsets. Command (TCommand) objects create a text command, such as an SQL statement, that can query or update a data source. If the text command specifies a row set, such as an SQL Select statement, it creates a row set. A single session can create multiple commands. Rowset (TRowset) objects expose data from a data source in a tabular format. Row sets can be created from a session or a command. An index object is a special case of a row set object. Error (TError) objects are created when errors occur when accessing a data provider. They include status, return codes, and an optional custom error object. SQLBase OLE DB Data Provider utilizes the custom error object.

For a list and detailed description of the supported interfaces for the COM objects above, read Microsoft OLE DB documentation or visit the Microsoft Web site.

5-2

Connecting to SQLBase

Data Source

Data Source
SQLBase OLE DB Data Provider uses the following Data Source (TDataSource) object interfaces:
Mandatory Optional

IDBCreateSession IDBInitialize IDBProperties IPersist

IDBInfo ISupportErrorInfo

Data Source properties


In addition to the properties inherited from its underlying classes, TDataSource has some specific properties of interest: DBPROP_INIT_PROVIDERSTRING This property can be used to supply up to three pieces of configuration information prior to making a connection to the database server. The parameter value, a string, must be formatted as follows:
INI=<ConfigFileName>;ims=<value>;oms=<value>

The configuration file name should include a fully qualified path. ims, input message buffer size, and oms, output message buffer size, can have a minimum value of 1 and a maximum value of 32000. (Default values are 2000 and 1000.) None of the three pieces of the string are required; any of them can be omitted. If there are two or more pieces in the string, the elements must be separated by semicolons.

Data Source descriptions


The following table briefly describes the data source interfaces and the level of support they receive.
Interface Name IDBCreateSession IDBInitialize Description Calls on a data source object to obtain a new session. Initialize and uninitialize data source objects. Support

Standard.
Standard, except enumerators are not supported.

Connecting to SQLBase

5-3

Chapter 5

Supported OLE DB COM Objects

Interface Name IDBProperties

Description Sets and gets properties values for the data source object. Returns the class identifier of an object. Returns a list of providerspecific keywords, or information about literals. Shows whether an interface can return automated error messages.

Support Standard, except enumerators are not supported. Standard. Optional interface is supported. SQLBase OLE DB COM objects that implement this interface also return error objects.

IPersist IDBInfo

ISupportErrorInfo

5-4

Connecting to SQLBase

Session

Session
SQLBase OLE DB Data Provider uses the following Session (TSession) object interfaces:
Mandatory IGetDataSource IOpenRowset ISessionProperties Optional IDBCreateCommand IDBSchemaRowset ISupportErrorInfo ITableDefinition IIndexDefinition ITransactionLocal ITransactionObject ITransactionJoin

Session descriptions
The following table briefly describes the session interfaces and the level of support they receive.
Interface Name IGetDataSource IOpenRowset Description IGetDataSource returns an interface pointer to the data source object. IOpenRowset opens and returns a rowset that includes all rows from a single base table or index. ISessionProperties returns information about the properties a session supports and the current settings of those properties. It is a mandatory interface on sessions. Consumers call IDBCreateCommand::CreateComm on a session to obtain a new command. IDBSchemaRowset provides advanced schema information. Support

Standard. Standard.

ISessionProperties

Standard.

IDBCreateCommand

Standard.

IDBSchemaRowset

Standard.

Connecting to SQLBase

5-5

Chapter 5

Supported OLE DB COM Objects

Interface Name ISupportErrorInfo

Description ISupportErrorInfo interface shows whether an interface can return automated error messages. The ITableDefinition interface exposes simple methods to create, drop, and alter data source tables. The IIndexDefinition interface exposes simple methods to create, drop, and alter data source indexes. ITransactionLocal is used to start, commit, and abort session transactions. It is optional ITransactionObject obtains the transaction object associated with a particular transaction level. ITransactionJoin allows your session to enlist in a distributed transaction,

Support

Standard.

ITableDefinition

Standard.

IIndexDefinition

Standard.

ITransactionLocal

Standard.

ITransactionObject

Standard.

ITransactionJoin

Standard

Command
SQLBase OLE DB Data Provider uses the following Command (TCommand) object interfaces:
Mandatory IAccessor IColumnsInfo ICommand ICommandProperties ICommandText IConvertType IColumnsRowset ICommandPrepare ICommandWithParameters ISupportErrorInfo Optional

5-6

Connecting to SQLBase

Command

Command Class Interface descriptions


The following table briefly describes the command class interfaces and the level of support they receive.
Interface Name IAccessor IColumsInfo Description The IAccessor describes how consumer buffer data is stored. IColumnsInfo exposes column information for a rowset or prepare command. Also, it provides limited information for an array. ICommand executes commands. This interface is mandatory on commands. ICommandProperties specifies properties from the Rowset property group to the command. When ICommandText is specified through SetCommandText, it replaces the existing command text. IConvertType provides command or rowset conversion type information. This interface is mandatory on commands, rowsets, and index rowsets. This interface supplies complete infomation about columns in a rowset. This optional interface encapsulates command optimization, a separation of compile time and run time. This interface encapsulates parameters. ISupportErrorInfo interface shows whether an interface can return automated error messages. Support

Standard. See Note.

ICommand ICommandProperties ICommandText

Standard. Standard. Standard.

IConvertType

Standard.

IColumnsRowSet ICommandPrepare

Standard. See Note.

ICommandWithParameters

Standard. Standard.

ISupportErrorInfo

Note: Because the SQLBase OLE DB provider exposes ICommandPrepare, there are important stipulations to using the IColumnsInfo interface. Please see the OLE DB Programmers Reference for further information.

Connecting to SQLBase

5-7

Chapter 5

Supported OLE DB COM Objects

Rowset
SQLBase OLE DB Data Provider uses the following Rowset (TRowset) object interfaces:
Mandatory IAccessor IColumnsInfo IConvertType IRowset IRowsetInfo Optional IRowsetErrorInfo ISupportErrorInfo IRowsetChange

Rowset Interface descriptions


The following table briefly describes the rowset interfaces and the level of support they receive.
Interface Name IAccessor IColumnsInfo Description The IAccessor describes how consumer buffer data is stored. IColumnsInfo exposes column information about rowset or prepared commands. It provides a limited set of array information. IConvertType provides command or rowset conversion type information. This interface is mandatory for commands, rowsets, and index rowsets. IRowset is the base rowset interface. It provides methods for fetching rows sequentially, getting the data from those rows, and managing rows. IRowset requires IAccessor and IRowsetInfo. IRowsetInfo provides information about a rowset. IRowsetInfo also provides methods for retrieving objects associated with the rowset. All rowsets must implement IRowsetInfo. Support

Standard. See Note.

IConvertType

Standard.

IRowset

Standard.

IRowsetInfo

Standard.

5-8

Connecting to SQLBase

Error

Interface Name IRowsetErrorInfo

Description IRowsetErrorInfo indicates whether a specific interface can return Automation error objects. ISupportErrorInfo interface shows whether an interface can return automated error messages.

Support

Standard.

ISupportErrorInfo

SQLBase OLE DB COM objects that implement this interface also return error objects. Provider cannot update rowsets derived from multiple tables. Does not support updating, deleting or inserting rows for Schema Rowset. The updates are immediate.

IRowsetChange

IRowsetChange has methods for updating the columns of existing rows, deleting existing rows, and adding new rows.

Note: Because the SQLBase OLE DB provider exposes ICommandPrepare, there are important stipulations to using the IColumnsInfo interface. Please see the OLE DB Programmers Reference for further information.

Error
SQLBase OLE DB Data Provider uses the following Error set (TError) object interfaces:
Mandatory IErrorInfo IErrorRecords None. Optional

Connecting to SQLBase

5-9

Chapter 5

Supported OLE DB COM Objects

Error Interface descriptions


The following table briefly describes the error interfaces and the level of support they receive.
Interface Name IErrorInfo Description IErrorInfo returns error & return code information. It returns the error message, component name, and GUID of the interface where the error occurred, and the name and Help file topic that applies to the error. OLE DB error objects expose IErrorInfo at two levels. IErrorRecords is defined by OLE DB. It is used to add and retrieve records for an OLE DB error object. Information is passed to and from OLE DB error objects in an ERRORINFO structure. ISQLErrorInfo returns the SQLSTATE & native error code. Support

Standard.

IErrorRecords

Standard.

ISQLErrorInfo

Standard.

5-10 Connecting to SQLBase

Connecting to SQLBase

Chapter 6

ADO Mapping to Gupta


This chapter provides isolation lever mapping to SQLBase. This chapter also provides tables that list, for each ADO object: The ADO method, property, or collection. The OLE DB method called. Whether or not it is supported by the SQLBase OLE DB Data Provider.

Connecting to SQLBase

6-1

Chapter 6

ADO Mapping to Gupta

Isolation level mapping


This table compares ADO isolation levels to SQLBase.
ADO Default adXactUnspecified adXactBrowse adXactChaos adXactCursorStability adXactIsolated adXactReadCommitted adXactReadUncommitted adXactRepeatableRead adXactSerializable SQLBase CS (cursor stability) Set to default (CS) RL (release lock) error CS (cursor stability) error CS (cursor stability) RL (release lock) RR (repeatable read) error

ADO mapping to Gupta interfaces


There is a table following for each of these objects: Command Connection Error Field Parameter Recordset

The tables use this nomenclature for ADO methods, properties, and collections: Method() .Property Collection[]

6-2

Connecting to SQLBase

Command object mapping

Command object mapping


ADO Method, Property, or Collection Execute() .ActiveConnection .CommandText .CommandTimeout .CommandType .Prepared Parameters[] ICommandPrepare::Prepare ICommandPrepare::Unprepare ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETERS ICommandWithParameters::SetParameterInfo IDBProperties::GetPropertyInfo ICommandProperties::GetProperties ICommandProperties::SetProperties ICommandText::SetCommandText ICommandProperties::SetCommandProperties (DBPROP_COMMANDTIMEOUT) OLE DB Method(s) called ICommand::Execute Support? Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

Properties[]

Connection object mapping


ADO Method, Property, or Collection BeginTrans() Close() CommitTrans() Execute() Open() RollBack() ITransactionLocal::Commit ICommand::Execute or IOpenRowset::OpenRowset IDBInitialize::Initialize IDBCreateSession::CreateSession ITransactionLocal::Abort OLE DB Method(s) called ITransactionLocal::StartTransaction Support? Yes Yes Yes Yes Yes Yes Yes Yes

Connecting to SQLBase

6-3

Chapter 6

ADO Mapping to Gupta

ADO Method, Property, or Collection OpenSchema() .Attributes .CommandTimeout .ConnectionTimeout .DefaultDatabase

OLE DB Method(s) called IDBSchemaRowset::GetRowset ITransactionLocal::Abort ICommandProperties::SetCommandProperties (DBPROP_COMMANDTIMEOUT) IDBProperties::SetProperties (DBPROP_INIT_TIMEOUT) IDBProperties::GetProperties (DBPROP_CURRENTCATALOG) IDBProperties::SetProperties (DBPROP_CURRENTCATALOG) ITransactionLocal::StartTransaction IDBProperties::GetProperties (DBPROP_INIT_MODE) IDBProperties::SetProperties (DBPROP_INIT_MODE) ISourcesRowset::GetSourcesRowset

Support? Yes Yes Yes Yes Yes Yes Yes Yes Yes

.IsolationLevel .Mode

.Provider .Version Errors[] Properties[]

Yes Yes

IErrorRecords IDBProperties::GetPropertyInfo IDBProperties::GetProperties IDBProperties::SetProperties

Yes Yes Yes Yes

Error object mapping


ADO Method, Property, or Collection .Description .HelpContent .HelpFile .NativeError OLE DB Method(s) called IErrorRecords::GetErrorInfo IErrorRecords::GetErrorInfo IErrorRecords::GetErrorInfo IErrorRecords::GetCustomErrorObject ISQLError::GetSQLInfo Support? Yes Yes Yes Yes Yes

6-4

Connecting to SQLBase

Field object mapping

ADO Method, Property, or Collection .Number .Source .SQLState

OLE DB Method(s) called

Support? Yes

IErrorRecords::GetErrorInfo IErrorRecords::GetCustomErrorObject ISQLError::GetSQLInfo

Yes Yes Yes

Field object mapping


ADO Method, Property, or Collection AppendChunk() GetChunk() .ActualSize .Attributes .DefinedSize .Name .NumericScale .OriginalValue .Precision .Type .UnderlyingValue .Value OLE DB Method(s) called ISequentialStream::Write ISequentialStream::Read IAccessor::CreateAccessor IRowset::GetData IColumnInfo::GetColumnInfo IColumnInfo::GetColumnInfo IColumnInfo::GetColumnInfo IColumnInfo::GetColumnInfo IRowsetUpdate::GetOriginalData IColumnInfo::GetColumnInfo IColumnInfo:GetColumnInfo IRowsetRefresh::GetLastVisibleData or IRowsetRefresh::GetVisibleData IAccessor::CreateAccessor IRowset::GetData IRowset::SetData IColumnsRowset::GetAvailableColumns IColumnsRowset::GetColumnsRowset Support? Yes Yes Yes Yes Yes Yes Yes Yes No Yes Yes No No Yes Yes Yes Yes Yes

Properties[]

Connecting to SQLBase

6-5

Chapter 6

ADO Mapping to Gupta

Parameter object mapping


ADO Method, Property, or Collection AppendChunk() .Attributes ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETERS ICommandWithParameters::SetParameterInfo ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETERS ICommandWithParameters::SetParameterInfo ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETERS ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETER ICommandWithParameters::SetParameterInfo ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETERS ICommandWithParameters::SetParameterInfo ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETERS ICommandWithParameters::SetParameterInfo ICommandWithParameters::GetParameterInfo or DBSCHEMA_PROCEDURE_PARAMETERS ICommandWithParameters::SetParameterInfo IAccessor::CreateAccessor ICommand::Execute OLE DB Method(s) called Support? Yes Yes (No) Yes Yes (No) Yes Yes (No) Yes (No) Yes Yes (No) Yes Yes (No) Yes Yes (No) Yes Yes Yes Yes

.Direction

.Name

.NumericScale

.Precision

.Size

.Type

.Value Properties[]

6-6

Connecting to SQLBase

Recordset object mapping

Recordset object mapping


ADO Method, Property, or Collection AddNew() CancelBatch() CancelUpdate() Clone() Close() Delete() GetRows() IRowsetLocate IAccessor::ReleaseAccessor IRowset::ReleaseRows IRowsetChange::DeleteRows IAccessor::CreateAccessor IRowsetLocate::GetRowsAt IRowset::GetNextRows IRowset::GetData IRowsetLocate::GetRowsAt or IRowset::GetNextRows IRowsetLocate::GetRowsAt or IRowset::RestartPosition IRowsetLocate::GetRowsAt IRowsetLocate::GetRowsAt or IRowset::GetNextRows IRowsetLocate::GetRowsAt or IRowset::GetNextRows IMultipleResults::GetResult IOpenRowset::OpenRowset or ICommand::Execute IOpenRowset::OpenRowset or ICommand::Execute IRowsetRefresh::RefreshVisibleData IRowsetInfo::GetProperties OLE DB Method(s) called IRowsetChange::InsertRow IRowsetUpdate::Undo Support? Yes No Yes No Yes Yes Yes Yes No Yes Yes No Yes No Yes No No Yes No Yes No Yes Yes Yes Yes No Yes

Move() MoveFirst() MoveLast() MoveNext() MovePrevious() NextRecordset() Open() Requery() Resync() Supports()

Connecting to SQLBase

6-7

Chapter 6

ADO Mapping to Gupta

ADO Method, Property, or Collection Update() UpdateBatch() .AbsolutePage

OLE DB Method(s) called IRowsetChange::SetData and/or IRowsetUpdate::Update IRowsetUpdate::Update IRowsetScroll::GetApproximatePosition IRowsetScroll::GetRowsAtRatio or IRowsetLocate::GetRowsAt IRowsetScroll::GetApproximatePosition IRowsetScroll::GetRowsAtRatio or IRowsetLocate::GetRowsAt IDBInitialize::Initialize IDBCreateSession::CreateSession

Support? Yes No No No No No No No No Yes Yes Yes

.AbsolutePosition

.ActiveConnection .BOF .Bookmark .CacheSize .CursorType .EditMode .EOF .Filter

IAccessor::CreateAccessor IRowsetLocate::GetRowsAt IRowsetLocate::GetRowsAt or IRowset::GetNextRows ICommandProperties::SetProperties IRowsetUpdate::GetRowsStatus

Yes No No Yes Yes No Yes

IRowsetUpdate::GetPendingRows IRowsetLocate::GetRowsByBookmark or IRowsetView::CreateView IRowsetView::OpenViewChapter IViewFilter::SetFilter ICommandProperties::SetProperties IOpenRowset::OpenRowset (DBPROP_MAXROWS) or ICommandProperties::SetCommandProperties (DBPROP_MAXROWS) IRowsetScroll::GetApproximatePosition (PageCount, AbsolutePage properties) IRowsetScroll::GetApproximatePosition

No No No No No Yes Yes Yes No No No

.LockType .MaxRecords

.PageCount .PageSize .RecordCount

6-8

Connecting to SQLBase

Recordset object mapping

ADO Method, Property, or Collection .Source .Status Fields[] Properties[]

OLE DB Method(s) called

Support? Yes

IRowsetUpdate::GetRowStatus IColumnInfo::GetColumnInfo IRowsetInfo::GetPropertyInfo IRowsetInfo::GetProperties IRowsetInfo::SetProperties

No Yes Yes Yes Yes

Connecting to SQLBase

6-9

Chapter 6

ADO Mapping to Gupta

6-10 Connecting to SQLBase

Connecting to SQLBase

Chapter 7

.NET Data Provider


SQLBase .NET requirements
You must have the .NET Framework already installed on your machine before the SQLBase .NET Data Provider will install correctly. Gupta recommends that you install the most recent service pack for the .NET Framework first. The SQLBase installation program offers you the option of installing the .NET Data Provider. You must choose this option to use the provider. The actual component name is Gupta.SQLBase.Data.DLL. It is registered as a .NET component during installation Any programming language that uses the provider will need to reference that component and its related namespace. For example, in Visual Basic.NET, you must choose menu item Project, Add Reference, locate the "Gupta SQLBase .NET Data Provider" item in the list on the ".NET" tab of the dialog, select it, and click OK. To reference the namespace, you must add a declaration to your code. In Visual Basic.NET, for example, you might do this with a line above your main code module:
Imports Gupta.SQLBase.Data

SQLBase .NET implementation


The current version of SQLBase provides objects that implement eight of the .NET interfaces. The vast majority of their functionality is identical to that described in the .NET Framework documentation for the class library. In this chapter, we will only

Connecting to SQLBase

7-1

Chapter 7

.NET Data Provider

document a property or method when there is something distinct about the way it is implemented in SQLBase. SQLBaseConnection: implements the IDbConnection interface, establishes a connection to a specific data source. SQLBaseCommand: implements the IDbCommand interface, executes a command against a data source, exposes parameters and can execute within the scope of a Transaction. SQLBaseDataReader: implements the IDataReader interface and reads a scrollable, read-only stream of data from a data source. SQLBaseDataAdapter: implements the IDataAdapter interface; populates a DataSet and resolves updates with the data source. SQLBaseTransaction: implements the IDbTransaction interface and represents a transaction to be performed at a data source. SQLBaseParameter: implements the IDataParameter interface, represents a parameter which can be passed to a SQL command. SQLBaseParameters: implements the IDataParameters interface, which is a simple collection of SQLBaseParameter objects. In addition to these eight objects, SQLBase provides SQLBaseException, a public interface/object which is used for throwing exceptions to a client in case of a SQLBase error during a client method call. These objects are inherited from standard classes in the Microsoft .NET Framework. This chapter does not document the methods and properties that are inherited from those standard classes; it focuses only on the methods and properties that are specific to Guptas implementation of the framework.

How-to information for the .NET data provider


How do SQLBase datatypes map to CLR datatypes?
SQLBase Type Integer Smallint Float Number Int32 Int16 Single Decimal CLR Type

7-2

Connecting to SQLBase

How-to information for the .NET data provider

SQLBase Type Double Decimal Date Time Timestamp Char Varchar Graphic Vargraphic Binary Varbinary Longvar Longvargraphic Longbinary Char>254 Varchar>254 Double

CLR Type

Decimal DateTime DateTime DateTime String String byte[] byte[] byte[] byte[] byte[] byte[] byte[] char[] char[]

How do I start a transaction?


See BeginTransaction on page 7-6, in the description of methods of the Connection object.

How do I set isolation levels?


Isolation level is specified as one of the parameters of BeginTransaction on page 7-6. Note that only some .NET isolation levels are supported by SQLBase.

How do I use long character data and long binary data?


In this example from the Tut5 application in samples\tutorials\vb.net, a dataset is created that includes a LONG VARCHAR column, and the data from that column is subsequently placed in a byte array that will be used to construct an image.
Connecting to SQLBase

7-3

Chapter 7

.NET Data Provider

' Setup the SQLBase connection string conn = New SQLBaseConnection("data source=island; uid = sysadm; pwd= sysadm; ini=D:\Gupta\SQLBase 8.5\sql.ini ") ' Open a connection to SQLBase conn.Open() ' Setup the Adapter's select command adaptor.SelectCommand() = New SQLBaseCommand("SELECT EMPLOYEE_ID, LAST_NAME, FIRST_NAME, EMAIL, " & _ "CURRENT_SALARY, PHOTO1 FROM EMPLOYEE", conn) ' Create a new DataSet ds = New DataSet() ' Fill the DataSet with the Adapter adaptor.Fill(ds, "EMPLOYEE") ' Close the database connection conn.Close() 'Create the array to store the picture

Dim arrPicture() As Byte = CType(ds.Tables(0).Rows(i)("PHOTO1"), Byte()) In this example from the Tut5 application in samples\tutorials\vb.net, an image is used to update the EMPLOYEES.PHOTO column in the ISLAND database. Variable FileByteArray was previously initialized with the bytes of the image.
' Setup the SQLBase connection string & open a connection to SQLBase conn = New SQLBaseConnection("data source=island; uid = sysadm; pwd= sysadm; ini=D:\Gupta\SQLBase 8.5\sql.ini ") conn.Open() 'Setup the Update SQL & Declare a Command Object UpdCmd = New SQLBaseCommand("UPDATE EMPLOYEE SET PHOTO1=:lsPhoto WHERE EMPLOYEE_ID=:sEmployeeID", conn) 'Add the parameters UpdCmd.Parameters.Add("lsPhoto", DbType.Binary, o.Length).Value = FileByteArray UpdCmd.Parameters.Add("sEmployeeID", DbType.String, "EMPLOYEE_ID").Value = txtEmployeeID.Text ' Execute the command If UpdCmd.ExecuteNonQuery() Then 'Close the database connection conn.Close() MessageBox.Show("Image Updated", "Message") SavePictureToDB = True End If

7-4

Connecting to SQLBase

How-to information for the .NET data provider

How do I run stored procedures?


The Visual Basic .NET code example below calls stored procedure COMPANY_SP2, which is part of the sample database ISLAND. The procedure accepts a single input parameter of type string (sName), containing a company name, and returns several string values, containing information from a row in the COMPANY table that matches the company name.
' Setup the SQLBase connection string. Be sure the "ini" argument points to the correct file. conn = New SQLBaseConnection("data source=island; uid = sysadm; pwd= sysadm; ini=c:\program files\Gupta\SQLBase90\sql.ini") ' Open a connection to SQLBase conn.Open() 'build a command that invokes stored procedure COMPANY_SP2 cmd = New SQLBaseCommand("COMPANY_SP2", conn) cmd.CommandType = CommandType.StoredProcedure 'COMPANY_SP2 requires one input parameter. It has four output parameters, ' but those don't need to be defined here. Dim sparam As SQLBaseParameter sparam = New SQLBaseParameter("sName", DbType.String) cmd.Parameters.Add(sparam) 'the actual reading of data could be done with a SQLBaseDataAdapter 'and a dataset, but in this case we use the SQLBaseDataReader. Dim Reader As SQLBaseDataReader 'initialize the value of the input parameter cmd.Parameters("sName").Value = TextName.Text call the stored procedure Reader = cmd.ExecuteReader() ' Insert code to read through the datareader. If Reader.Read() Then TextAddress.Text = Reader.GetString(0) TextCity.Text = Reader.GetString(1) TextState.Text = Reader.GetString(2) TextZip.Text = Reader.GetString(3) End If

' Close the database connection conn.Close()

Connecting to SQLBase

7-5

Chapter 7

.NET Data Provider

SQLBaseConnection object
For information about the methods, properties and events inherited from IDbConnection see the .NET Framework documentation.

SQLBaseConnection properties
ConnectionString
This property supplies basic information about the data source. It can contain multiple keyword=value parameters separated by semicolons, as described below:
datasource|data source|ds|database|db=data source name string; userid|user id|uid=user id string; password|pwd=password string; poolsize|pool size=integer; connection lifetime=integer; ims=integer; oms=integer;)

All keywords except the first one are optional. Keywords are not case-sensitive. In cases where more than one keyword has the same meaning, the keywords are shown separated by pipe symbols in the diagram above. ims (input message buffer) and oms (output message buffer) are described in detail in the Configuration Files chapter of the Database Administrators Guide.

SQLBaseConnection methods
BeginTransaction
Syntax Description
IDbTransaction BeginTransaction ( IsolationLevel)

Start a new transaction.


Parameters

IsolationLevel

string. SQLBase supports the following values in the IsolationLevel parameter: ReadUncommitted (SQLBase Release Lock); ReadCommitted (SQLBase Cursor Stability); RepeatableRead (SQLBase Repeatable Read); Unspecified (SQLBase Repeatable Read).

Use of other unsupported isolation level values, such as Chaos or Serializable, will cause a SQLBase exception with "Unsupported isolation level : xxx." message. Related methods Commit and Rollback are also supported by the SQLBaseConnection object.

7-6

Connecting to SQLBase

SQLBaseConnection object

ChangeDatabase
Syntax Description
void ChangeDatabase (string dbname )

This method is not supported by SQLBase. Calling this method will throw a NotSupportedException exception to the caller.

Close
Syntax Description
void Close()

This method logically closes your database connection. The connection may be cached rather than physically closed; for details on this, read Connection pooling in the Open method on page 7-8.

CreateCommand
Syntax Description
IDbCommand CreateCommand( )

Initialize a new SQLBaseCommand object.

GetSQLBaseSchemaTable
Syntax Description
DataTable GetSQLBaseSchemaTable (schemaGuid, restrictions)

Return a DataTable object containing schema information for the currently connected database. SQLBase supports the following types of schema information:
SQLBaseSchemaGuid.Tables SQLBaseSchemaGuid.Columns SQLBaseSchemaGuid.Tables_Info SQLBaseSchemaGuid.Provider_Type SQLBaseSchemaGuid.Catalogs SQLBaseSchemaGuid.Foreign_Keys SQLBaseSchemaGuid.Primary_Keys SQLBaseSchemaGuid.Indexes SQLBaseSchemaGuid.Procedures SQLBaseSchemaGuid.Views SQLBaseSchemaGuid.Column_Privileges SQLBaseSchemaGuid.Table_Privileges

Parameters

schemaGuid

instance of class SQLBaseSchemaGuid

Connecting to SQLBase

7-7

Chapter 7

.NET Data Provider

restrictions

string

Open
Syntax Description
void Open( connection_string )

Opens a database connection. When you call this method, SQLBase will attempt to reuse an existing open database connection from the connection pool. If this is not possible, it will create a new database connection. connection_string string. See the detailed descriptoin of this parameter in property ConnectionString, above.

Parameters

Connection pooling in the Open method


SQLBase provides two of the keywords in the connection string parameter of the Connect method to assist with connection pooling. poolsize indicates how many SQLBase connections should be kept open, whether they are in immediate use or not. The default value is 5. connection lifetime indicates how long each connection should be maintained, in seconds. The default value is 60. These defaults are stored in the Windows registry under key HKEY_LOCAL_MACHINE\Software\Gupta\SQLBase\DotNetDataProvider. Each connection pool is specific to the application that calls the Connect method. When the number of active connections is still below or at the poolsize limit, connections that have been closed by the application remain cached (physically open and available for new connection requests) until their lifetime is reached, at which time they are physically disconnected. Each call to Connect resets the current values for poolsize and connection lifetime. Gupta recommends that you avoid issuing Connect calls in which the new value for poolsize is smaller than the one currently being used by the application.

SQLBaseCommand object
For information about the methods, properties and events inherited from IDbCommand, see the .NET Framework documentation. The SQLBaseCommand object is often initialized from the CreateCommand method of the SQLBaseConnection class. To release that class underlying database cursor, it is important to call the Dispose method of SQLBaseCommand when your processing is finished. Otherwise the command object is released either when the connection is released or the garbage collector releases the object, and both of these will be quite late in most circumstances. In addition, relying upon the garbage collector may mean incomplete release of all resources connected to the command object, raising the possibility of eventually running out of resources in an application with heavy use of SQLBaseCommand objects.

7-8

Connecting to SQLBase

SQLBaseCommand object

SQLBaseCommand properties
CommandText
You should set the value of the CommandText property of the object before any other methods are called. For a Text Command type (see CommandType property), the CommandText property should contain a valid SQL statement. For a Stored Procedure type, the CommandText property should contain a procedure name. For a Table Direct type, the CommandText property should contain a table name.

CommandType
SQLBase supports three types of command objects: TextCommand, StoredProcedure, and TableDirect. The default type of each command object, upon creation, is Text Command. You are responsible for changing this type, if necessary, by altering the CommandType property of the object.

SQLBaseCommand methods
Cancel
Syntax Description
void Cancel ( )

Attempts to cancel the execution of a command. This method is not supported in SQLBase, and will throw a NotSupportedException when called.

GetSQLBaseParameter
Syntax Description
void GetSQLBaseParameter ( parametertype, value, length )

Retrieves the value of an interal SQLBase parameter. SetSQLBaseParameter and GetSQLBaseParameter are not part of the IDbCommand interface. They manipulate the many SQLBase internal parameters. Detailed documentation for these parameters is available in the SQLBase SQL Application Programming Interface Reference, under the function sqlset.

Parameters

parametertype value length

string. One of the many parameter names defined in the SQLBase API Reference. string, pass by reference. Contains the value returned from SQLBase. integer, pass by reference. Buffer length of value.

SetSQLBaseParameter
Syntax Description
void SetSQLBaseParameter ( parametertype, value, length )

Attempts to set a SQLBase parameter value 7-9

Connecting to SQLBase

Chapter 7

.NET Data Provider

SetSQLBaseParameter and GetSQLBaseParameter are not part of the IDbCommand interface. They manipulate the many SQLBase internal parameters. Detailed documentation for these parameters is available in the SQLBase SQL Application Programming Interface Reference, under the function sqlset.
Note: This method should be used only by advanced SQLBase developers. Calling this method while in the middle of a transaction can potentially cause unpredictable results in the transaction or the database.

Parameters

parametertype value length

string. One of the parameter names documented in the SQLBase API Reference. string. The value to be assigned to the parameter. integer. The length in bytes of value.

SQLBaseDataReader object
For information about the methods, properties and events inherited from IDataReader, see the .NET Framework documentation. This object provides the capability of reading a scrolling result set obtained by executing a command against a data source. SQLBase supports only a single result set. Datatypes are mapped to CLR-compatible types as described in How do SQLBase datatypes map to CLR datatypes? on page 7-2. To make use of scrolling result sets, property SQLBaseCommand.ResultSetMode must be set to TRUE. The SQLBaseDataReader object implements interface IEnumerable, with a single method, GetEnumerator, which returns an IEnumerator object. That object has methods MoveNext and Reset, and get/set property RowPos (current row of result set), which allow you to move to a specific row in the result set.

SQLBaseDataReader methods Get... methods


Syntax
Int16 GetInt16 (index) Int32 GetInt32 (index) Int64 GetInt64 (index) Single GetFloat (index) byte GetByte (index) char GetChar (index)

7-10 Connecting to SQLBase

SQLBaseDataReader object

Double GetDouble (index) Decimal GetDecimal (index) Guid GetGuid (index) DateTime GetDateTime (index) TimeSpan GetTime (index) Boolean GetBoolean (index) String GetString (index) Object GetValue (index)

Description

Each of these methods retrieves a single value from a column in the dataset. The specific method chosen is dependent on the datatype of the column. If parameter index is not valid, exception IndexOutOfRange is thrown. index int. The position of the column in the result set.

Parameters

Get methods for long (BLOB) data


Syntax Description
long GetBytes (index, offset, buffer, readBytes) long GetChars (index, offset, buffer, readBytes)

Reads bytes or characters from a column with a long datatype. If index is not found, throws exception IndexOutOfRange. Returns the number of bytes actually read, or, if buffer is null, the length of the column. index offset buffer readBytes Long. Relative position of the column in the row. long. Offset within the long data column at which reading is to begin. Zero-based. byte[] or char[], depending on method. Buffer to hold the results of the read. long. Number of bytes to read into buffer.

Parameters

GetDataTypeName
Syntax Description Parameters
string GetDataTypeName (index)

Get the SQLBase (not CLR) datatype for the specified column. If index is not found, throws exception IndexOutOfRange. index int. Position of column in the result set.

GetFieldType
Syntax Description
Type GetFieldType (index)

Return the .NET system type for the specified column. If index is not found, throws exception IndexOutOfRange.

Connecting to SQLBase

7-11

Chapter 7 Parameters

.NET Data Provider

index

int. Position of column in the result set.

GetName
Syntax Description Parameters
string GetName (index)

Get the column (field) name for the specified column. If index is not found, throws exception IndexOutOfRange. index int. Position of column in the result set.

GetOrdinal
Syntax Description
Int16 GetOrdinal (column)

Returns the ordinal (position in the row, beginning with one) of the column named in parameter column. If the column name is not found, throws exception IndexOutOfRange. column int. The position of the column in the result set.

Parameters

GetValues
Syntax Description
int GetValues (objectArray)

Retrieves multiple values into an array of objects, rather than retrieving a single value as the other Get... methods do. It returns the actual number of valus that were retrieved: objectArray Object. An array of type Object that will receive values for each column in the result set. If there are fewer elements in the array than there are columns in the result set, then the method will fill only those elements, then stop.

Parameters

IsDbNull
Syntax Description Parameters
bool IsDbNull (index)

Checks the specified column for a null value, and returns TRUE if found, or FALSE if not found. If index is not found, throws exception IndexOutOfRange. index offset of column

NextResult
Syntax Description
bool NextResult ( )

Moves to the next result set. SQLBase supports only a single result set, so calls to this method always return FALSE.

7-12 Connecting to SQLBase

SQLBaseDataAdapter object

SQLBaseDataAdapter object
This class does not inheirt from SqlDataAdapter, since that class contains logic that is specific to Microsoft SQL Server. However, its function is quite similar; a data adapter has a database connection and a group of commands that are designed to move data from the database into a data set object. This class inherits from the more general DbDataAdapter class. For information about the methods, properties and events inherited from DbDataAdapter, see the .NET Framework documentation. The methods of this class are all inherited from the standard DbDataAdapter class, which can be found in the Microsoft .NET Framework documentation. To complete the functionality of this class, SQLBase must implement four properties that are found in the DbDataAdapterInterface. Each of these properties has Get and Set methods.

SQLBaseDataAdapterProperties
DeleteCommand
Contains the text of a SQL query used to delete records.

InsertCommand
Contains the text of a SQL query used to insert new records.

SelectCommand
Contains the text of a SQL query used to select records. When a .NET client calls the dataAdapter.Fill ( ) method it will execute the command which is contained in the SelectCommand property. The command object will return a IDataReader interface to the data adapter after executing the command , and the data adapter will use that interface to get data from the data source and fill the System.DataSet object. After that client can manipulate the data in in the DataSet object through DataSet methods.

UpdateCommand
Contains the text of a SQL query used to update records. When a .NET client calls the dataAdapter.Update ( ) method it will execute the three commands contained in the UpdateCommand, InsertCommand and DeleteCommand properties, and update the data source through these commands with the changes in the DataSet.
Connecting to SQLBase

7-13

Chapter 7

.NET Data Provider

SQLBaseTransaction object
For information about the methods, properties and events inherited from IDbTransaction, see the .NET Framework documentation.

SQLBaseTransaction Properties
Connection
Datatype: SQLBaseConnection. The Connection object which should be passed to this object in the constructor.

IsolationLevel
Datatype: IsolationLevel. Get only. The IsolationLevel enumeration which should be passed to this object in the constructor from the connections BeginTransaction ( ) method.

SQLBaseTransaction methods
Commit
Syntax Description
void Commit ( )

Commit the database transaction. The current transaction is complete. The client should call BeginTransaction method from the Connection object to start a transaction again.

Rollback
Syntax Description
void Rollback ( )

Roll back a transaction from a pending state.

SQLBaseParameter object
For information about the methods, properties and events inherited from IDbTransaction, see the .NET Framework documentation. This object has four properties and no methods. You must set its properties to appropriate values before supplying this object to the SQLBaseCommand object before execution.

Properties
DbType: DbType
Get/Set. The CLR datatype of the parameter. 7-14 Connecting to SQLBase

SQLBaseParameters object

String: ParameterName
Get/Set. The name that the command object uses to refer to the parameter.

String: SourceColumn
Get/Set. Links this parameter to a column in a DataSet object.

Object: Value
Get/Set. The actual value assigned to this parameter.

SQLBaseParameters object
This object is basically a collection of SQLBaseParameter objects. The Add method is overloaded in five ways.

Add
Syntax Description Parameters
SQLBaseParameter Add (value)

Add value object.

Syntax Description Parameters

SQLBaseParameter Add (value)

text value SQLBaseParameter

Syntax Description Parameters

SQLBaseParameter Add (parametername, type)

text parametername type string. Name of the parameter DbType. Datatype of the parameter.

Syntax Description Parameters

SQLBaseParameter Add (parametername, value)

text parametername value string. Name of the parameter. object. Value of the parameter.

Connecting to SQLBase

7-15

Chapter 7

.NET Data Provider

Syntax Description Parameters

SQLBaseParameter Add(parameterName, dbType, column)

text parametername type column string. Name of the parameter. DbType. Datatype of the parameter. string. Data set column associated with the parameter.

SQLBaseException object
This object handles all errors returned by SQLBase.

SQLBaseException Properties
int: ErrorCode
Get only. The SQLBase numeric code of the error.

int: ErrorPosition
Get only. The offset in the command text where the error was detected.

String: ErrorMessage
Get only. The description of the error.

SQLBase classes and transaction state


It is possible in the .NET framework to write code that could disrupt the state of a SQLBase transaction. To prevent this disruption, the SQLBaseCommand class will throw an exception if you try to change its Transaction property to anything other than the result of the last call to SQLBaseConnection.BeginTransaction:
Failed to set transaction for the command. The transaction is not compatible with the connection.

The exception guards against situations like the example below: Open a SQLBaseConnection object named conn Create a SQLBaseCommand object against conn named cmd Create a SQLBaseTransaction object named txn by calling the conn.BeginTransaction method. (Now this database connection is logically

7-16 Connecting to SQLBase

SQLBase classes and transaction state

inside a transaction.) The commands belonging to the connection, including cmd, will acquire txn in their Transaction property. Set the cmd.Transaction property to null. (This would mean that the command no longer participates in the txn transaction.) Execute the command. Commit but how? The Commit method is part of the SQLBaseTransaction class, and we have set cmd.Transaction to null, so we have no object to use for calling that method.

Because you changed the SQLBaseCommand.Transaction property, the SQLBase connection is now in an inconsistent state, running a pending SQLBase engine transaction that cant or wont be committed because the necessary .NET transaction is no longer associated with that connection. The .NET interface definitions imply that you can have a command object whose Transaction property points to a transaction created under some other database connection, not the connection used when the command was initialized. Despite this theoretical possibility, Gupta recommends that you think of the connection, transaction and command objects as a set that reference each other. This is a more accurate reflection of how the SQLBase engine works internally a commit on a SQLBase connection commits all the cursors that are active against that connection. So, from the .NET viewpoint, a call to cmd.Transaction.Commit will commit not just cmd, but all other commands that belong to the same connection. Note that this concept also applies if your application is running some commands under a transaction and other commands without a transaction. In this situation, the commands belonging to the transaction need a separate connection of their own.

To summarize this issue in two brief rules:


1. Whatever its current value, you must not change the SQLBaseCommand.Transaction property to a different value. If you attempt to do this, an exception will be thrown. If you wish to have multiple transactions active simultaneously in your application, make sure that you have a separate SQLBaseConnection object associated with each transaction, and make sure that the SQLBaseCommand objects relevant to that transaction also belong to the same connection. A transaction and a connection have a one-to-one relationship that must not be altered.

2.

Connecting to SQLBase

7-17

Chapter 7

.NET Data Provider

7-18 Connecting to SQLBase

Connecting to SQLBase

Chapter 8

Introduction to the JDBC driver


This chapter describes specific issues relating to the Gupta SQLBase JDBC (Java Database Connectivity) Driver. For general information on JDBC Drivers, we recommend you visit java.sunt.com or read one of the many published books on JDBC Drivers. The example source code shown in this chapter is derived from the files available in the Samples subdirectory of the SQLBase program directory (presuming that you asked to install samples during installation.)

Introduction
The SQLBase JDBC driver supports applications written using JDBC 1.3.1 and higher. It is a Type 4 Driver according to the definition published by Javasoft, meaning that it is a native-protocol driver which converts JDBC calls into the network TCP/IP protocol used by the database server, requiring no additional middle layer components of either the client or the server. The SQLBase JDBC Driver is therefore both thin and portable. Using this driver, developers can create Java applets that connect to remote SQLBase databases resident on Web Servers, or create Java applications that connect to SQLBase databases on either local or remote machines, using SQLBase's existing TCP/IP protocol support.

Connecting to SQLBase

8-1

Chapter 8

Introduction to the JDBC driver

JDK Versions
There are multiple versions of the Java Development Kit (JDK). This driver is compatible with JDK 1.1.x and higher. Modern Web browsers such as Netscape Communicator version 4 and higher, and Microsoft Internet Explorer version 4 and higher, support JDK 1.1.x, including JDBC functionality.

Installation
Tested Platforms
This driver has been tested on Windows 98, ME, NT, 2000, Server 2003, and XP, and (for Linux) on Red Hat 9.0, Red Hat Advanced Server 3.0, SUSE 9.0, SUSE Enterprise Server 8.0, SUSE Desktop 1.0.

Getting Started
Windows
You can request JDBC support during the initial install of SQLBase The default directory for SQLBase itself is c:\program files\gupta\SQLBase90. Presuming you also install the JDBC driver to this directory, then after installation, the following files and directories will be found. c:\program files\gupta\SQLBase90\Java\SQLBaseJDBC.jar - Contains the JDBC class files. c:\program files\gupta\SQLBase90\Samples - Contains a set of sample JDBC application programs as tutorials.

Linux
JDBC support is an option at the time of installation in Linux. If you use the default installation directory, the following file will be installed: /opt/Gupta/SQLBase90/java/SQLBaseJDBC.jar - JDBC class files

CLASSPATH
To allow the Java Virtual Machine to load the SQLBase JDBC Driver locally or at the host-of-origin, the standard Java system environment variable CLASSPATH must be modified to include the root directory containing the JDBC classes. For example, if you chose the SQLBase default directory as your installation directory, you would set the variable as follows on Windows:

8-2

Connecting to SQLBase

SQLBase Support for JDBC

SET CLASSPATH=%CLASSPATH%;C:\program files\gupta\java\SQLBaseJDBC.jar

And on Linux, if you chose the default installation directory, CLASSPATH would be altered like this:
export CLASSPATH=$CLASSPATH:/opt/Gupta/SQLBase90/java/SQLBaseJDBC.jar

Server Configuration
The server should be configured to listen on TCP/IP protocols. For more information regarding the use of TCP/IP, please refer to the SQLBase Database Administrator's Guide chapter on communications.

SQLBase Support for JDBC


SQL Operations Support
The SQLBase JDBC Driver is designed to access relational database over the Internet or an Intranet. It currently supports common DDL and DML operations.

DDL Operations Support


All DDL operations, such as creating tables, dropping tables, and creating indices are supported. Operations which require a server connection, such as loading and unloading, backup, and restore are not supported in this release of the JDBC Driver since such connections are not supported by JDBC.

DML Operations Support


Most DML operations such as insertions, deletions, updates, selects (including data binding), long varchars, and stored procedures are supported. The "ADJUSTING" clause of the INSERT keyword is not supported.

Multiple Connection Support


The SQLBase JDBC Driver supports the multiple connection model of SQLBase 7.0 and higher. An application can establish multiple connections ("cursor handles") to a SQLBase Server, and transactions committed for one connection are completely independent of transactions committed for another connection.

Multi-threading Support
The JDBC Driver is implemented to be thread safe. An application can use multiple threads to perform operations on various tables while the user continues to interact with the application.

Connecting to SQLBase

8-3

Chapter 8

Introduction to the JDBC driver

It is NOT recommended that JDBC objects (i.e. Statement, ResultSet etc.) are shared between threads because an object's internal state can be corrupted by interleaved threads. Each thread should operate privately on JDBC objects.

Transaction Model
The transaction model is uniform between the SQLBase ODBC Driver and the JDBC Driver.
Isolation Level TRANSACTION_NONE TRANSACTION_READ_COMMITTED TRANSACTION_SERIALIZABLE TRANSACTION_READ_UNCOMMITTED TRANSACTION_REPEATABLE_READ Description AutoCommit plus RL (release locks) isolation CS (cursor stability) Not Supported (Creates an Exception) Not Supported (Creates an Exception) RR

For SQLBase specific applications or applets that require a strict SQLBase transaction model, the SQLBase JDBC Driver provides an extended TRANSACTION MODE as indicated below:
Isolation Level TRANSACTION_SQLBase_RL TRANSACTION_SQLBase_RR TRANSACTION_SQLBase_CS TRANSACTION_SQLBase_RO Description RL (release locks) isolation RR (read repeatability) isolation CS (cursor stability) isolation RO (read only) isolation

The default TRANSACTION isolation for the JDBC Driver is TRANSACTION_REPEATABLE_READ.

How-to information for the JDBC driver


How do SQLBase datatypes map to JDBC datatypes?
See SQLBase Supported Data Types: on page 8-8

8-4

Connecting to SQLBase

How-to information for the JDBC driver

How do I start a transaction?


A code fragment illustrating a simple transaction is shown below. Changing the setting of AuoCommit implicitly starts a new transaction.
Connection con1 = DriverManager.getConnection(url, "SYSADM", "SYSADM"); con1.setAutoCommit(false); Statement stmt1 = con1.createStatement(); try {stmt1.executeUpdate("DROP TABLE TESTAC1"); catch (SQLException se) // Do nothing if table does not exist } stmt1.executeUpdate("CREATE TABLE TESTAC1 (C1 INT, C2 CHAR(10))"); con1.commit(); stmt1.close();

How do I set isolation levels?


Use method setTransactionIsolation, as shown below.
Connection con1 = DriverManager.getConnection(url, "SYSADM", "SYSADM"); con1.setTransactionIsolation(Connection.TRANSACTION_NONE);

The supported isolatoin levels are shown in Transaction Model on page 8-4.

How do I use long character data and long binary data?


In this code fragment from sample program longs.java, included with SQLBase, you can see methods getAsciiStream and setAsciiStream are used to bind long data to specific symbol positions in a SQL query statement. In this example, the number 1 used as the first parameter in the method refers to the second column or second bind variable (in a zero-based list).
stmt.executeUpdate("create table test(c1 int, c2 long varchar)"); con1.commit(); System.out.println("inserting long data"); //Inserting Long Data java.io.File file = new java.io.File("longs.txt"); long fileLength = file.length(); java.io.InputStream fin = new java.io.FileInputStream(file); java.sql.PreparedStatement pstmt = con1.prepareStatement("INSERT INTO test VALUES (1,?)");

Connecting to SQLBase

8-5

Chapter 8

Introduction to the JDBC driver

stmt.setAsciiStream(1, fin,(int)fileLength); pstmt.executeUpdate(); //Fetching Long Data byte [] buff = new byte[4096]; ResultSet rs = stmt.executeQuery("SELECT c2 FROM test WHERE c1 = 1 "); while (rs.next ()) { fin = rs.getAsciiStream(1);

How do I run stored procedures?


See Stored procedure support on page 8-11

URL formats
Examples of use of the standard formats are illustrated below:
jdbc:sqlbase://localhost[:2157]/island [;ims=;oms=] jdbc:sqlbase://server1[:2157]/island [;ims=;oms=] jdbc:sqlbase://198.95.xxx.xx:2156/island [;ims=;oms=]

URL keywords:
jdbc:sqlbase: is the JavaSoft registered URL keyword for SQLBase localhost is used to refer to the host name of the local machine server1 is the host name of the machine server1 The default port used by SQLBase to receive incoming TCP/IP requests is 2155. It needs to be specified only when a different port number is being used by the SQLBase server, in which case it follows the host name or IP address, separated by a colon. island is the database where this URL is intended to connect. 198.95.xxx.xx is an IP address. ims (optional) is input message buffer size. Use a value from 1 to 32000. If no value or an invalid value is specified, the default of ims=2000 will be used. oms (optional) is output message buffer size. Use a value from 1 to 32000. If no value or an invalid value is specified, the default of oms=1000 will be used.

Data types and conversions


SQLBase data types do not map completely to Java data types. The following conversion table is provided to show the mapping between SQLBase storage types and the Java data types: 8-6
Connecting to SQLBase

Data types and conversions

Explanation of keys:
Key C D E W * Description Conversion is done - a conversion warning is issued for accuracy check Date crash is done Throw exception - this conversion is not allowed Field width and data width mismatch - a truncation warning is issued for loss of digits No warning - a valid get/set is performed

Connecting to SQLBase

8-7

Chapter 8

Introduction to the JDBC driver

SQLBase Supported Data Types:


JDBC Data Type CHAR NUM DATE LONG DT TIME CHAR NUMBER, INTEGER, DECIMAL, FLOAT, DOUBLE, REAL DATE LONGVARCHAR DATETIME TIME SQL Data Type

For READING Operations using ResultSet:


CHAR W C C C C C C C C * C C C * NUM W * C W W W W W W C C C C C DATE W E E E E E E E E C * C C C LONG W E E E E E E E E * E E E * W E E E E E E E E C C C * C DT TIME W E E E E E E E E C C * C C ResultSet Methods getString from CHAR,VARCHAR getBigDecimal from NUMERIC getBool from BIT getByte from TINYINT getShort from SMALLINT getInt from INTEGER getLong from BIGINT getFloat from REAL getDouble from DOUBLE getBytes[] ** getDate from DATE getTime from TIME getTimestamp from TIMESTAMP getStream from LONGVARCHAR

** same as getStream from VARBINARY or LONGVARBINARY 8-8


Connecting to SQLBase

SQLBase Supported Data Types:

Datatypes example
This example shows the use of various methods (setString, setShort, etc.) in preparing bind variable datatypes. Similar methods (getString, getShort, etc.) are used when retrieving individual values from result sets.
public class InsertDataTypes { private static String url = "jdbc:sqlbase://localhost:2155/ ISLAND"; private static void executeUpdate(Statement stmt, String sql ) { try { stmt.executeUpdate(sql); }catch (Exception ex) { System.out.println("'" + sql + "' failed with: " + ex); } } public static void main (String args[]) { try { Class.forName("jdbc.gupta.sqlbase.SqlbaseDriver"); if ( args.length > 0 && args[0].length() > 0) { url = args[0]; } // ENDIF Get Connection URL Connection con1 = DriverManager.getConnection( url, "SYSADM", "SYSADM"); Statement stmt = con1.createStatement(); try { executeUpdate(stmt, "drop table foosh"); } catch (Exception e) { System.out.println("e = " + e.getMessage()); } String sQuery = "Create table foosh (C1 char(10)," + "C2 varchar(10), C3 dec(8,2), C4 integer," + "C5 smallint, C6 float," + " C7 datetime, C8 time, C9 date)"; executeUpdate(stmt, sQuery); con1.commit(); System.out.println("Will insert 9 columns to the row"); PreparedStatement pStmt = con1.prepareStatement ( "Insert into foosh values(?,?,?,?,?,?,?,?,?)");

Connecting to SQLBase

8-9

Chapter 8

Introduction to the JDBC driver

java.sql.Datex = java.sql.Date.valueOf("1999-11-31"); java.sql.Timestampy = java.sql.Timestamp.valueOf("1998-1130 12:59:59.0"); Time z = Time.valueOf("23:30:15"); short a = 8; pStmt.setString(1,"Sushi"); pStmt.setString(2,"Wushi"); pStmt.setDouble (3,6789.98); pStmt.setInt (4,31); pStmt.setShort (5,a); pStmt.setFloat (6,18.0f); pStmt.setTimestamp(7,y); pStmt.setTime(8,z); pStmt.setDate(9,x); int n = pStmt.executeUpdate(); Statement stmt1 = con1.createStatement(); ResultSet rs = stmt1.executeQuery("select C1,"+ "C2,C3,C4, C5, C6, C7,C8,C9 from foosh"); while (rs.next()) { String s1 = rs.getString(1); String s2 = rs.getString(2); double d = rs.getDouble("c3"); int i = rs.getInt(4); float f = rs.getFloat(6); java.sql.Timestamp d1 = rs.getTimestamp(7); java.sql.Time d2 = rs.getTime(8); java.sql.Date d3 = rs.getDate(9); System.out.println("C1 System.out.println("C2 System.out.println("C3 System.out.println("C4 System.out.println("C5 System.out.println("C6 System.out.println("C7 System.out.println("C8 } con1.commit(); con1.close(); } catch (Exception ex) { System.out.println("Exception in main: " + ex); = = = = = = = = " + i); " + s1); " + d); " + i); " + f); " + d1); " + d2); " + d3);

8-10 Connecting to SQLBase

Bind variable support

} } }

Bind variable support


The SQLBase JDBC Driver supports the bind variable escape character '?' in a SQL statement. The driver attempts to parse the '?' from the input SQL statement. The parser skips over '?' characters that are used within single quoted expression constants or double quoted identifier to avoid disruption of the syntax of the SQL statement. The example source code above, for datatypes, also illustrates the use of bind variables within SQL queries.

Stored procedure support


The SQLBase JDBC Driver supports the CallableStatement { call ?,... } syntax. However, since SQLBase Stored Procedures do not support any OUT parameters, a SQLException will be thrown when the CallableStatement.registerOutParameter(...) method is called. This restriction also invalidates the [? =] portion of the { [? =] call ?,... } syntax. SQLBase stored procedures return the result via a ResultSet. After executing the CallableStatement, a getResult() method can be called to retrieve result data. ResultSetMetaData is also helpful in determining the column types, column lengths and other information about the result data. To provide input parameters, the CallableStatement.setXXX() methods can be called to pass Java data types from the caller to the stored procedure as bind data.

Stored procedure example


This program does an insert on execution of a procedure. To prepare for this test you need to do some work on the database. First, you need to make sure there is a table named FOO (C1 int,C2 char(10)) in database ISLAND. Second, you need to store the following procedure ...
STORE JAVA_PROC_1 PROCEDURE: JAVA_PROC_1 PARAMETERS Number: x ACTIONS On Procedure Execute Call SqlImmediate('insert into foo values(:x, \'Gupta\')')

Connecting to SQLBase

8-11

Chapter 8

Introduction to the JDBC driver

When you are done, you can drop FOO and ERASE JAVA_PROC_1 ..now, the example program.
import java.io.*; import java.util.*; import java.sql.*; public class Proc { private static String url ISLAND";

= "jdbc:sqlbase://localhost:2155/

public static void main (String args[]) { try { Class.forName("jdbc.gupta.sqlbase.SqlbaseDriver"); if ( args.length > 0 && args[0].length() > 0) { url = args[0]; } // ENDIF Get Connection URL Connection con = DriverManager.getConnection(url, "SYSADM", "SYSADM"); CallableStatement cstmt = con.prepareCall("{call Java_Proc_1}"); cstmt.setInt(1,45); cstmt.executeUpdate(); con.commit(); // Is it there? Statement s = con.createStatement(); ResultSet r = s.executeQuery("SELECT C1,C2 FROM FOO"); while (r.next()) { int i = r.getInt(1); String str = r.getString(2); System.out.println("C1: " + i + " C2: " + str); } cstmt.close(); s.close(); con.close(); } catch (Exception ex) { System.out.println("\nException in main: " + ex + "\n"); System.out.println("Unable to access or execute procedure Java_Proc_1"); } } }

8-12 Connecting to SQLBase

Named Cursor Support

Named Cursor Support


Cursor naming is supported by the SQLBase JDBC Driver. Cursor names are generally used in conjunction with the WHERE CURRENT OF clause of an UPDATE or DELETE statement. After the cursor name is set for a Statement or PreparedStatement object (using method setCursorName) the executeQuery() can be called to prepare a SELECT statement.
Connection con1 = DriverManager.getConnection( url, "SYSADM", "SYSADM"); con1.setTransactionIsolation(Statement stmt2 = con1.crea Connection.TRANSACTION_REPEATABLE_READ); ... Statement stmt2 = con1.createStatement(); stmt2.setCursorName("C2"); Statement stmt1 = con1.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT C1,C2 FROM FOO FOR UPDATE OF C1");

The cursor name can then be used by other Statement or PreparedStatement objects with the WHERE CURRENT OF clause in SQL statements.
while (rs.next()) { int k = rs.getInt(1); String s = rs.getString(2); if (k == 2) executeUpdate(stmt1, "UPDATE FOO SET C1 = 200 WHERE CURRENT OF C2");

Error Message Support


This release provides a simplified version of error message text from error.sql. However, in order to keep the memory consumption down and the SQLBase JDBC thin, error tokens, reason and remedy are not supported.

Application and Applet Development


Java Virtual Machine reserves the java.xxx.xxx package for its own libraries. Generally, any library that is not part of the JVM cannot use the java.xxx.xxx package. The java.xxx.xxx package is critical to applets. Loading a library from unrecognized java.xxx will result in "class not found" exception being thrown by the SecurityManager. To avoid this problem, the SQLBase JDBC Driver is normally packaged under the jdbc.gupta.sqlbase.* package.

Connecting to SQLBase

8-13

Chapter 8

Introduction to the JDBC driver

If you encounter problems during execution of the sample Java programs, you should examine CLASSPATH to ensure that it contains a path to the location of the SQLBase JDBC Driver classes. To allow the SQLBase error text to be displayed by the JDK 1.1.x line of the SQLBase JDBC Driver, the error.html file must be copied to the WWW root directory or the <HOME> directory of the system where the SQLBase JDBC Driver is installed, in this case the host-of-origin.

Restrictions
All of the documented JDBC API is included in this release. Certain functionality of the API is neither completely supported, directly relevant nor necessarily supportable by SQLBase. Where this occurs, SQLException will be thrown with the "...not supported..." message.

Network Check
Network check (netcheck) is not implemented in the SQLBase JDBC Driver. If network check is set in the SQL.INI file for the SQLBase server, the JDBC driver may not be able to communicate with the server.

SQLWarning Support
In general, SQLBase does not support warnings. However, the warning processing using SQLWarning is implemented in the SQLBase JDBC Driver for trapping potential problems generated during data conversion.

Encrypted Databases
Applications using the JDBC Driver cannot connect to encrypted SQLBase databases.

NLS and DBCS Databases


The JDBC Driver supports non-US databases. Please refer to the file CountrySetting.java file in the samples directory for more information on how to connect to non-US databases. DBCS databases are also supported in this release.

8-14 Connecting to SQLBase

Glossary
Connecting to SQLBase A Abort To return the values changed by a transaction to their original state. Accessor A collection of information that describes how data is stored in the consumer's buffer. The provider uses this information to determine how to transfer data to and from this buffer. See also reference accessor. Accessor handle A handle that identifies an accessor. Auto-commit mode A transaction commit mode in which all actions taken in a transaction are committed immediately after they are performed. B Binary large object (BLOB) Any binary or character data over a certain number of bytes, such as 255. Typically much longer. Such data is generally sent to and retrieved from the data source in parts. Also known as long data. Binding As a verb, the act of associating a column in a rowset or a parameter in a text command with a consumer variable. As a noun, the association or the DBBINDING structure that describes the association. Bookmark A value that identifies a row in a rowset. Bookmarks are saved by the consumer and used later in the life of the rowset to retrieve a particular row. BSTR A pointer to a null-terminated character string in which the string length is stored with the string. B-tree A tree structure for storing database indexes. Buffer A piece of memory used to pass information, usually data, between the consumer and provider.
Connecting to SQLBase

-1

Glossary

C Catalog A database object that contains one or more schemas. Change To update, delete, or insert a row of data. Class ID A globally unique identifier (GUID) associated with an OLE class object. If a class object will be used to create more than one instance of an object, the associated server application should register its CLSID in the system registry so that clients can locate and load the executable code associated with the object(s). Every OLE server or container that allows linking to its embedded objects must register a CLSID for each supported object definition. Client/server A database access strategy in which one or more clients access data through a server. The clients generally implement the user interface while the server controls database access. Column The container for a single item of information in a row. Also known as field. Column ID A structure used to identify a column, primarily in a command where there are no stable ordinals or column names. COM object An object that conforms to the OLE Component Object Model (COM). A COM object is an instance of an object definition, which specifies the object's data and one or more implementations of interfaces on the object. Clients interact with a COM object only through its interfaces. See also Component Object Model and interface. Command An OLE DB object that encapsulates a command. Command text The text command associated with a command object. Although it is not required to be, this is usually an SQL statement. Commit To make the changes in a transaction permanent. Component An object that encapsulates both data and code, and provides a wellspecified set of publicly available services. Component Object Model (COM) The OLE object-oriented programming model that defines how objects interact within a single process or between processes. In COM, clients have access to an object through interfaces implemented on the object. See also interface. Concurrency The ability of more than one transaction to access the same data at the same time. Consumer Software that calls OLE DB methods and interfaces. Container A file containing linked or embedded objects. Convert To change data from one type to another, such as from an integer to a string. -2

Connecting to SQLBase

Coordinated transaction A transaction composed of multiple, subordinate transactions. All of the subordinate transactions must succeed for the coordinated transaction to succeed. Also known as a distributed transaction. CoType A way to define a group of COM objects, such as rowsets or commands, that have similar characteristics. All COM objects that belong to a particular CoType must expose the mandatory interfaces in that CoType. In addition, they can expose the optional interfaces in the CoType and any interfaces not in the CoType. D Data The data for a parameter in a text command or a column in a row. Data Definition Language (DDL) Those text commands that define, as opposed to manipulate, data. For example, the SQL statements CREATE TABLE, CREATE INDEX, GRANT, and REVOKE. Data Manipulation Language (DML) Those text commands that manipulate, as opposed to define, data. For example, the SQL statements INSERT, UPDATE, DELETE, and SELECT. Data part Data has three parts: the data value, the length of the data value, and the status of the data value. Data provider A provider that directly exposes data, as opposed to a service component. Data source The data the user wants to access, such as the data in a database, file, or array. This is distinct from a data source object. Data source object An OLE DB object that connects to a data source. This is distinct from the data source. Data type The type of a piece of data. See also type indicator. Database A discrete collection of data in a DBMS. Also a DBMS. Database Management System (DBMS) A layer of software between the physical database and the user. The DBMS manages all access to the database. An OLE DB provider can be built directly on top of a DBMS or as a layer between the DBMS and the consumer. Deferred column A column for which the data is not instantiated in the rowset until the consumer actually attempts to access that data. Delayed update mode An update mode in which changes made through IRowsetChange are cached in the rowset and transmitted to the data source only when IRowsetUpdate::Update is called. See also immediate update mode. Delete To remove an existing row of data from the data source.
Connecting to SQLBase

-3

Glossary

Distributed transaction See coordinated transaction. Dynamic error An error message that cannot be predicted because it is not provider specific.Dynamic error ID An identifier that is used by a lookup service and is associated with an error object. E Empty string A zero-length string. See also null pointer and NULL value. Endogenous change A change to data originating from a process other than your own. Enumerator An OLE DB object that searches for data sources and other enumerators. See also root enumerator. Error A condition in which a fatal error occurred. Also used to refer to any error, regardless of whether it is fatal. Error code A class of return code, of the type HRESULT, that begins with E_ or DB_E_ and indicates that the method failed completely and was unable to do any useful work. Error lookup service A method used by a provider to handle and interpret OLE DB error objects. Error object An object that contains detailed information about an error. See also OLE Automation error object and OLE DB error object. Event An action taken by a provider, such as changing a column value or deleting a row, of which the provider notifies the consumer. Execution plan A plan generated by a query engine to execute a command. Equivalent to executable code compiled from a third-generation language such as C. F Fetch To retrieve one or more rows from the data source and instantiate them in a rowset. Field See column. Fixed-length data type A data type that is always stored in the same number of bytes, such as a two-byte integer. See also variable-length data type. Foreign key A column or columns in a table that match the primary key in another table. G

-4

Connecting to SQLBase

Getting data Transferring data from the provider to the consumer, as in getting column or output parameter data. Globally Unique Identifier (GUID) A 16-byte value that uniquely identifies something, usually the software that implements one or more COM objects or an interface on one of those objects. Also known as a UUID (Universally Unique Identifier). H Handle A value that uniquely identifies something such as a row or an accessor. Handles are meaningful only to the software that creates and uses them, but are passed by other software to identify things. HRESULT An opaque result handle defined to be zero for a successful return from a function and nonzero if error or status information is returned. I Interface Identifier (IID) A globally unique identifier (GUID) associated with an interface. Some functions take IIDs as parameters to allow the caller to specify which interface pointer should be returned. Immediate update mode An update mode in which changes made through IRowsetChange are immediately transmitted to the data source. See also delayed update mode. Index rowset A rowset built over an index. Each row in an index rowset contains a bookmark that points to a row in a rowset built over the corresponding table. Initialize To change the state of an enumerator or data source object so it can be used to access data. For example, initializing a data source object might require the provider to open a data file or connect to a database. Input parameter A parameter in a text command for which the consumer supplies a value to the provider. Input/output parameter A parameter in a text command for which the consumer supplies a value to the provider and the provider returns a value to the consumer. Insert To add a new row of data to the data source. Instantiate To create an instance of a COM object. Interface A group of semantically related functions that provide access to a COM object. Each OLE interface defines a contract that allows objects to interact according to the Component Object Model (COM). Although OLE provides many interface implementations, most interfaces can also be implemented by developers designing OLE applications. See also Component Object Model and COM object. -5

Connecting to SQLBase

Glossary

IPersist* object An OLE object that supports IPersistStream, IPersistStreamInit, or IPersistStorage. Isolation level See transaction isolation level. J JDBCA set of Java classes which standardizes access to any vendors database from Java applications or applets. Join An operation in a relational database that links the rows in two or more tables by matching values in specified columns. K Key A column or columns whose values identify a row. See also primary key and foreign key. Key value bookmark A bookmark that uses a unique key to identify a row. See also numeric bookmark. L Length The length of a data value. See also data part, value, and status. Listener A consumer that has requested that a provider send it notifications of various events. Long data See BLOB. M Manual-commit mode A transaction commit mode in which transactions must be explicitly committed or aborted by calling ITransaction::Commit or ITransaction::Abort. Maximum precision The maximum number of base 10 digits that can be stored in a particular data type. See also precision. Metadata Data that describes a parameter in a text command or a column in a rowset. For example, the data type, length, and updatability of a column. Method A function in an interface. Moniker A name for a specific object instance. Multiple results object An OLE DB object created by executing a command and through which multiple results (rowsets or row counts) can be retrieved. N Next fetch position The position of the next row that will be fetched by a call to IRowset::GetNextRows. -6

Connecting to SQLBase

Notification A call from a provider to a consumer, in which the provider notifies the consumer that a particular event is occurring. Notification sink An actual object that implements the notification interface. Null pointer A pointer with a value of zero. It is an error to dereference a null pointer. See also empty string and NULL value. NULL value Having no explicitly assigned value. In particular, a NULL value is different from a zero or a blank. See also empty string and null pointer. Numeric bookmark A bookmark that uses a unique number to identify a row. See also key value bookmark. O Object In OLE, a programming structure encapsulating both data and functionality that are defined and allocated as a single unit and for which the only public access is through the programming structure's interfaces. A COM object must support, at a minimum, the IUnknown interface, which maintains the object's existence while it is being used and provides access to the object's other interfaces. See also Component Object Model and interface. ODBC Microsofts earliest standard for OLE Microsoft's object-based technology for sharing information and services across process and machine boundaries. OLE Automation error object An error object that conforms to the standards specified for such objects by OLE Automation. See also OLE DB error object. OLE DB A set of interfaces that expose data from a variety of data sources using COM. OLE DB error object An error object used by OLE DB objects to return an error. OLE DB error objects are an extension of Automation error objects. OLE DB object A COM object defined by OLE DB. The COM objects defined by OLE DB are enumerators, data source objects, sessions, commands, rowsets, multiple results objects, OLE DB error objects, transaction objects, and transaction options objects. OLE DB Software Development Kit (SDK) A collection of redistributable software, header files, tools, sample code, and documentation to be used by developers of OLE DB consumers and providers. OLE object In OLE DB, a COM object that is stored in a column. In OLE, a COM object.

Connecting to SQLBase

-7

Glossary

Optimistic concurrency A strategy to increase concurrency in which rows are not locked. Instead, before they are updated or deleted, a rowset checks to see if they have been changed since they were last read. If so, the update or delete fails. See also pessimistic concurrency. Ordinary bookmark A bookmark whose value is defined by the provider. See also standard bookmark. Output parameter A parameter in a text command for which the provider returns a value to the consumer. P Parallel processing A method of processing that can run only on a computer that contains two or more processors running simultaneously. Parameter A variable in a text command. A parameter can be an input, input/output, or output parameter. Pending change A change that has been cached in a rowset and not yet transmitted to the data source. See also delayed update mode and immediate update mode. Persist To save the current state of a COM object, such as to a file. Currently, only data source objects can be persisted. Pessimistic concurrency A strategy for implementing serializability in which rows are locked so that other transactions cannot change them. See also optimistic concurrency. Phase A step in a sequence of notifications caused by a single event. The sequence of notifications is similar to the phases in a two-phase commit protocol. Precision The number of base 10 digits in a number. See also maximum precision. Prepare To compile a command. An execution plan is created by preparing a command. Preserved rowset A rowset in which all previously defined functionality is retained after a commit or abort. Primary key A column or columns that uniquely identifies a row in a table. Procedure A group of one or more precompiled commands (generally SQL statements) that are stored as a named object in a database. Property Attributes of an OLE DB object. For example, the maximum number of rows in a rowset that can be active at one time. Property group The set of all properties that apply to a particular OLE DB object. Property set A property is identified by a GUID and an integer (the property ID). A property set is the set of all properties that share the same GUID. -8
Connecting to SQLBase

Provider Software that implements OLE DB methods and interfaces. Q Query A text command. Sometimes used to mean a text command that creates a rowset. R Reason The specific event that occurred, such as changing a row value or deleting a row. Record See row. Reference counting Keeping a count of each interface pointer held on an object to ensure that the object is not destroyed before all references to it are released. In OLE DB, rows and accessors are also reference counted. Reference accessor An accessor that enables a consumer to get rowset data directly from the provider's buffer. Support for reference accessors is optional. Release To decrease the reference count on a row, accessor, or COM object. When the reference count reaches zero, the provider generally releases the resources used by the row, accessor, or COM object. Result A row count or rowset created by executing a command. See also multiple results object. Resynchronize To update the data in a rowset with the data in the data source that is visible to the current transaction according to its isolation level. Return code The value returned by an OLE DB method. Root enumerator An enumerator shipped in the OLE DB SDK that enumerates the data sources and enumerators listed in the registry. See also enumerator. Row A set of related columns that describe a specific entity. Also known as a record. Row handle A handle used to identify a row. Rowset An OLE DB object that contains a set of rows, each of which has columns of data. S Scale The number of digits in a number that are to the right of the decimal point. Schema A database object that contains one or more tables, often created by a single user. Schema rowset A predefined rowset that provides information about the structure of a database.

Connecting to SQLBase

-9

Glossary

Self bookmark A bookmark, stored in column 0 of a row, that is used to return to that row. Serializability Whether two transactions executing simultaneously produce a result that is the same as the serial (or sequential) execution of those transactions. Serializable transactions are required to maintain database integrity. Service component A provider that does not directly expose data, but instead provides a service, such as query processing. Used in conjunction with data providers. Session An OLE DB object that serves as the context for a transaction. Setting data Transferring data from the consumer to the provider, as in setting column or input parameter data. SQL Structured Query Language. A language used by relational databases to query, update, and manage data. Text commands often use SQL. Standard bookmark A bookmark whose value is defined by OLE DB. See also ordinary bookmark. Static error An error (text) that is stored by a specific provider lookup service, and most commomly tied to a single data store. Status The status of a data value. See also data part, value, and length. Storage interface An interface used to access data in a storage object: ISequentialStream, IStream, IStorage, or ILockBytes. Storage object A COM object that implements a storage interface. Storage objects are used to access BLOB data and OLE objects stored in a column. Success A condition in which no errors occurred. Success code A class of return code, of the type HRESULT, that begins with S_ or DB_S_ and indicates success of the method. T Table A collection of rows in the data source. Text command A text string, usually an SQL statement, that defines a command. Transaction An atomic unit of work. The work in a transaction must be completed as a whole; if any part of the transaction fails, the entire transaction fails. Transaction isolation The act of isolating one transaction from the effects of all other transactions. Transaction isolation level A measure of how well a transaction is isolated. Transaction object An OLE DB object used to support transactions. -10
Connecting to SQLBase

Transaction options object An OLE DB object used to define various options for a transaction. Transfer To move data between the consumer's and provider's buffers. The provider, not the consumer, transfers data. See also getting data and setting data. Transmit To send changes made through IRowsetChange to the data source. See also delayed update mode and immediate update mode. Transmitted change A change that has been sent to the data source. See also pending change. Truncate To discard one or more bytes of variable-length data or non-significant digits of numeric data. Truncation results in a warning condition when getting data and an error condition when setting data. Type indicator An integer value passed to or returned from an OLE DB method to indicate the data type of a consumer variable, a parameter, or a column. U Uninitialize To change the state of an enumerator or data source object so it cannot be used to access data. For example, uninitializing a data source object might require the provider to close a data file or disconnect from a database. Unprepare To discard the current execution plan. Update To change an existing row of data in the data source. Also, to transmit pending changes to the data source. User The end user, which is a generally a person, as opposed to the consumer, which is a piece of software. V Value A data value. See also data part, length, and status. Variable-length data type A data type for which the length of the data can vary, such as a string. See also fixed-length data type. Visibility Whether data values can be detected by a rowset. Refers both to the visibility of data in a data source and data cached in a rowset. W Warning A condition in which a nonfatal error occurred. Warning code A class of return code, of the type HRESULT, that begins with S_ or DB_S_ and indicates success of the method but with a warning. Z

Connecting to SQLBase

-11

Glossary

Zombie A state in which the only valid consumer action on a COM object is generally to release that object.

-12

Connecting to SQLBase

Index
Symbols
.NET exceptions 7-16 transactions 7-16 ConnectionString property 7-6 Connectivity Administrator 1-2 Crystal Reports 4-4 cursor object 4-8 cursors 4-7

A
ActiveX Data Objects 4-3 ADO 4-3, 4-6 coding sample 4-12 adoid.h 4-8 adoint.h 4-8 adojavas.inc 4-8, 4-10 adovbs.inc 4-8 Advanced Data Connector 4-7 apartment-model 4-8 applet 8-13 application developers 1-10

D
Data Access Objects 4-7 data consumer 4-2 data provider 4-2 data source 4-4, 4-14 COM object 5-2 interfaces 5-3 DBExplore.exe 4-11 DBPROP_INIT_PROVIDERSTRING 5-3 DeleteCommand property 7-13 Delphi 4-4 disconnect 4-15 Dynamic Properties 4-9

B C

batch updates 4-7, 4-10 BOF 4-13

E
EOF 4-13 error COM object 5-2 interfaces 5-9 routine 4-15 trapping 4-14 error object 4-8, 6-4 Errors collection 4-11, 4-12 escape character 8-11

C++ 4-8 caching 4-7 CLASSPATH 8-2 closing 4-15 collections 4-9, 6-2 COM 4-2 cotypes 5-2 objects 5-1 COM+ 1-9 command COM object 5-2 interfaces 5-6 command object 4-8, 6-3 CommandText 7-9 CommandText property 7-9 CommandType property 7-9 Component Object Model 4-2 configuring the provider 4-4 connecting 4-10 using ADO 4-11 Connection 7-8 connection lifetime 7-6 connection object 4-8, 6-3 Connection pooling 7-8 connection pooling 2-7 connection string 7-8

F
fetch 4-13 field object 4-8, 6-5

H
header file 4-10 hierarchy 4-8

I
IEnumerable 7-10 IEnumerator 7-10 InsertCommand property 7-13 iODBC 2-9 ISLAND sample database 4-9, 4-10 IsNull 4-13

J
Java 4-7
SQLBase OLE DB Data Provider Users Guide

-1

Index

Java Development Kit 8-2 Java Type Library Wizard 4-7 Java Virtual Machine 8-13 JDBC 8-1 bind variables 8-11 data types 8-6 isolation levels 8-4 JScript 4-8, 4-10

L
last record 4-16 libraries ADO 4-7 Linux 2-9 Long Binary 4-11 Long text fields 4-11

parameter object 4-8, 6-6 password 4-4, 4-14 PHP 3-3 poolsize 7-6 PowerBuilder 4-4 previous record 4-16 program ID 4-7 properties 4-8, 6-2 Properties collections 4-10 property object 4-8 provider name 4-4, 4-9 provider string 4-14

R
reading 4-2 Recordset object 4-9 recordset object 4-8, 6-7 Remote Data Objects 4-7 Remote Data Service 4-7 RowPos 7-10 rowset COM object 5-2 interfaces 5-8

methods 4-8, 6-2 Microsoft Visual J++ 4-7 MTS 1-9

N
named cursor 8-13 navigation 4-14 NULL values 4-13

S
sample applications 4-10 schema 4-11 Scripting code 4-10 scrollable 4-10 scrolling result sets 7-10 SelectCommand property 7-13 session COM object 5-2 interfaces 5-5 simplefetch 4-10, 4-12 SQL.INI 1-2 SQL/API functions 4-2 SQLBaseCommand Cancel 7-9 GetSQLBaseParameter 7-9 SetSQLBaseParameter 7-9 SQLBaseCommand object 7-8 SQLBaseConnection 7-6 BeginTransaction 7-6 ChangeDatabase 7-7 Close 7-7 CreateCommand 7-7

O
objects ADO 4-8 ODB data types 2-7 ODBC 2-1 see Chapter 10 Conformance 2-4 connection string 3-1 data source properties 2-8 driver 2-2 driver manager 2-2 isolation 2-4 overview 2-2 supported functions 2-5 ODBC API 4-2 odbc.ini 2-9 odbcinst 2-9 odbcinst.ini 2-9 Open DataBase Connectivity see ODBC

-2

SQLBase OLE DB Data Provider Users Guide

GetSQLBaseSchemaTable 7-7 Open 7-8 SQLBaseDataAdapter object 7-13 SQLBaseDataReader Get methods 7-10 Get methods for long (BLOB) data 7-11 GetDataTypeName 7-11 GetFieldType 7-11 GetName 7-12 GetOrdinal 7-12 GetValues 7-12 IsDbNull 7-12 NextResult 7-12 SQLBaseDataReader object 7-10 SQLBaseParameter object 7-14 SQLBaseParameters Add 7-15 SQLBaseParameters object 7-15 SQLBaseSchemaGuid 7-7 SQLBaseTransaction Commit 7-14 Rollback 7-14 SQLBaseTransaction object 7-14 stored procedure 8-11 stored procedures 4-7 Supported ODBC Functions 2-5

T
TCP/IP 1-9 TextBox objects 4-13 Threading 4-8 Transaction Model 8-4 transaction state 7-16

U
Universal Data Access 4-2 unixODBC 2-9 update 4-15 UpdateCommand property 7-13

V
VBScript 4-8 Visual Basic 4-4

W
Web sites 4-6

SQLBase OLE DB Data Provider Users Guide

-3

Index

-4

SQLBase OLE DB Data Provider Users Guide

S-ar putea să vă placă și