Connecting To Your Database For PB
Connecting To Your Database For PB
Appeon PowerBuilder®
2017
DOCUMENT ID: DC37776-01-1700-01
This publication pertains to Appeon software and to any subsequent release until otherwise indicated in new editions or technical notes.
Information in this document is subject to change without notice. The software described herein is furnished under a license agreement,
and it may be used or copied only in accordance with the terms of that agreement.
Upgrades are provided only at regularly scheduled software release dates. No part of this publication may be reproduced, transmitted, or
translated in any form or by any means, electronic, mechanical, manual, optical, or otherwise, without the prior written permission of
Appeon Limited.
Appeon and other Appeon products and services mentioned herein as well as their respective logos are trademarks or registered
trademarks of Appeon Limited.
SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of
SAP and SAP affiliate company.
Java and all Java-based marks are trademarks or registered trademarks of Oracle and/or its affiliates in the U.S. and other countries.
Unicode and the Unicode Logo are registered trademarks of Unicode, Inc.
All other company and product names mentioned may be trademarks of the respective companies with which they are associated.
Use, duplication, or disclosure by the government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of DFARS 52.227-7013
for the DOD and as set forth in FAR 52.227-19(a)-(d) for civilian agencies.
Appeon Limited, 1/F, Shell Industrial Building, 12 Lee Chung Street, Chai Wan District, Hong Kong
Contents
iv PowerBuilder Classic
Contents
vi PowerBuilder Classic
Contents
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise . 287
SAP Adaptive Server Enterprise Name qualification ................... 288
SAP Adaptive Server Enterprise SQL functions .......................... 288
SAP Adaptive Server Enterprise Transaction management statements
290
SAP Adaptive Server Enterprise Using CONNECT, COMMIT,
DISCONNECT, and ROLLBACK.................................... 290
SAP Adaptive Server Enterprise Using AutoCommit ................... 291
SAP Adaptive Server Enterprise Performance and locking ......... 292
SAP Adaptive Server Enterprise Non-cursor statements............. 295
SAP Adaptive Server Enterprise DELETE, INSERT, and UPDATE ...
296
SAP Adaptive Server Enterprise SELECT ................................... 296
SAP Adaptive Server Enterprise Cursor statements.................... 299
SAP Adaptive Server Enterprise Retrieval Using Cursors ........... 300
SAP Adaptive Server Enterprise Closing the Cursor ................... 303
SAP Adaptive Server Enterprise Database stored procedures.... 304
SAP Adaptive Server Enterprise Retrieval ................................... 305
SAP Adaptive Server Enterprise DECLARE and EXECUTE ....... 306
SAP Adaptive Server Enterprise FETCH ..................................... 307
SAP Adaptive Server Enterprise CLOSE..................................... 308
SAP Adaptive Server Enterprise Update ..................................... 309
SAP Adaptive Server Enterprise Return values and output parameters
311
SAP Adaptive Server Enterprise Temporary tables ..................... 313
SAP Adaptive Server Enterprise System stored procedures ....... 313
x PowerBuilder Classic
Contents
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server .................. 337
Microsoft SQL Server Name qualification .................................... 338
Microsoft SQL Server Functions .................................................. 338
Microsoft SQL Server Transaction management statements ...... 339
Microsoft SQL Server Using CONNECT, COMMIT, DISCONNECT, and
ROLLBACK .................................................................... 340
Microsoft SQL Server Using AutoCommit .................................... 341
Microsoft SQL Server Performance and locking .......................... 342
Microsoft SQL Server Non-cursor statements ............................. 345
Microsoft SQL Server DELETE, INSERT, and UPDATE ............. 345
Microsoft SQL Server SELECT .................................................... 346
Microsoft SQL Server Cursor statements .................................... 348
Microsoft SQL Server Fetching rows ........................................... 350
Microsoft SQL Server FETCH NEXT ........................................... 350
PART 7 APPENDIX
Audience This book is for anyone who uses PowerBuilder® to connect to a database. It
assumes that you are familiar with the database you are using and have
installed the server and client software required to access the data.
How to use this This book describes how to connect to a database in PowerBuilder by using a
book standard or native database interface. It gives procedures for preparing,
defining, establishing, maintaining, and troubleshooting your database
connections. For an overview of the steps you need to take, see Basic
connection procedure on page 3.
Related documents For detailed information about supported database interfaces, DBParm
parameters, and database preferences, see the Database Connectivity section in
the PowerBuilder Help. For a complete list of PowerBuilder documentation,
see PowerBuilder Getting Started.
Other sources of Use the Appeon Product Manuals web site to learn more about your product.
information The Appeon Product Manuals web site is accessible using a standard Web
browser.
To access the Appeon Product Manuals web site, go to Product Manuals at
https://www.appeon.com/developers/library/product-manuals-for-pb.
Conventions The formatting conventions used in this manual are:
Formatting example Indicates
Retrieve and Update When used in descriptive text, this font indicates:
• Command, function, and method names
• Keywords such as true, false, and null
• Datatypes such as integer and char
• Database column names such as emp_id and
f_name
• User-defined objects such as dw_emp or
w_main
If you need help All customers are entitled to standard technical support for reproducible
software defects. You can open a standard support ticket at the Appeon
support site: https://www.appeon.com/standardsupport/ (login required).
If your organization has purchased a premium support contract for this product,
then the designated authorized support contact(s) may seek assistance with
your technical issue or question at the Appeon support site:
https://support.appeon.com (login required).
ii PowerBuilder
PA RT 1 Introduction to Database
Connections
1
CHAPTER 1 Understanding Data Connections
About this chapter This chapter gives an overview of the concepts and procedures for connecting
to a database in the PowerBuilder development environment.
Contents
Topic Page
How to find the information you need 3
Accessing data in PowerBuilder 5
Accessing the Demo Database 6
Using database profiles 6
What to do next 11
4 PowerBuilder
CHAPTER 1 Understanding Data Connections
Loading database PowerBuilder loads the libraries used by a database interface when it connects
interface libraries to the database. PowerBuilder does not automatically free the database
interface libraries when it disconnects.
Although memory use is somewhat increased by this technique (since the
loaded database interface libraries continue to be held in memory), the
technique improves performance and eliminates problems associated with the
freeing and subsequent reloading of libraries experienced by some database
connections.
If you want PowerBuilder to free database interface libraries on disconnecting
from the database (as it did prior to PowerBuilder 8), you can change its default
behavior:
To change the default
behavior for Do this
Connections in the Select the Free Database Driver Libraries On
development Disconnect check box on the General tab of the System
environment Options dialog box
Runtime connections Set the FreeDBLibraries property of the Application
object to TRUE on the General tab of the Properties view
in the Application painter or in a script
6 PowerBuilder
CHAPTER 1 Understanding Data Connections
What you can do Using database profiles is the easiest way to manage data connections in the
PowerBuilder development environment. For example, you can:
• Select a database profile to connect to or switch between databases
• Edit a database profile to customize a connection
• Delete a database profile if you no longer need to access that data
• Import and export database profiles to share connection parameters
quickly
For more information For instructions on using database profiles, see Chapter 13, Managing
Database Connections.
Database Profiles The Database Profiles dialog box uses an easy-to-navigate tree control format
dialog box to display your installed database interfaces and defined database profiles. You
can create, edit, and delete database profiles from this dialog box.
When you run the PowerBuilder Setup program, it updates the Vendors list in
the PowerBuilder® section in the HKEY_LOCAL_MACHINE registry key
with the interfaces you install. The Database Profiles dialog box displays the
same interfaces that appear in the Vendors list.
For detailed instructions on using the Database Profiles dialog box to connect
to a database and manage your profiles, see Chapter 13, Managing Database
Connections.
Database Profile Each database interface has its own Database Profile Setup dialog box where
Setup dialog box you can set interface-specific connection parameters. For example, if you
install the Adaptive Server Enterprise ASE interface and then select it and click
New in the Database Profiles dialog box, the Database Profile Setup - Adaptive
Server Enterprise dialog box displays, containing settings for the connection
options that apply to this interface.
8 PowerBuilder
CHAPTER 1 Understanding Data Connections
The Database Profile Setup dialog box groups similar connection parameters
on the same tab page and lets you easily set their values by using check boxes,
drop-down lists, and text boxes. Basic (required) connection parameters are on
the Connection tab page, and additional connection options (DBParm
parameters and SQLCA properties) are on the other tab pages.
As you complete the Database Profile Setup dialog box in PowerBuilder, the
correct PowerScript® connection syntax for each selected option is generated
on the Preview tab. You can copy the syntax you want from the Preview tab
into a PowerBuilder application script.
Supplying sufficient For some database interfaces, you might not need to supply values for all boxes
information in the in the Database Profile Setup dialog box. If you supply the profile name and
Database Profile
Setup dialog box click OK, PowerBuilder displays a series of dialog boxes to prompt you for
additional information when you connect to the database.
This information can include:
User ID or login ID
Password or login password
Database name
Server name
For some databases, supplying only the profile name does not give
PowerBuilder enough information to prompt you for additional connection
values. For these interfaces, you must supply values for all applicable boxes in
the Database Profile Setup dialog box.
For information about the values you should supply for your connection, click
Help in the Database Profile Setup dialog box for your interface.
3 On the Connection tab page, type the profile name and supply values for
any other basic parameters your interface requires to connect.
For information about the basic connection parameters for your interface
and the values you should supply, click Help.
4 (Optional) On the other tab pages, supply values for any additional
connection options (DBParm parameters and SQLCA properties) to take
advantage of DBMS-specific features that your interface supports.
For information about the additional connection parameters for your
interface and the values you should supply, click Help.
5 (Optional) Click the Preview tab if you want to see the PowerScript
connection syntax that PowerBuilder generates for each selected option.
You can copy the PowerScript connection syntax from the Preview tab
directly into a PowerBuilder application script.
For instructions on using the Preview tab to help you connect in a
PowerBuilder application, see the section on using Transaction objects in
Application Techniques.
6 Click OK to save your changes and close the Database Profile Setup dialog
box. (To save your changes on a particular tab page without closing the
dialog box, click Apply.)
10 PowerBuilder
CHAPTER 1 Understanding Data Connections
The Database Profiles dialog box displays, with the new profile name
highlighted under the appropriate interface. The database profile values
are saved in the system registry in
HKEY_CURRENT_USER\Software\Sybase\PowerBuilder\17.0\Database
Profiles\PowerBuilder.
You can look at the registry entry or export the profile as described in
Importing and exporting database profiles on page 177 to see the settings
you made. The NewLogic parameter is set to True by default. This setting
specifies that the password is encrypted using Unicode encoding.
What to do next
For instructions on preparing to use and then defining an ODBC data source,
see Chapter 2, Using the ODBC Interface.
For instructions on preparing to use and then defining a JDBC database
interface, see Chapter 3, Using the JDBC Interface.
For instructions on preparing to use and then defining an OLE DB data
provider, see Chapter 4, Using the OLE DB Interface.
For instructions on preparing to use and then defining an ADO.NET data
provider, see Chapter 5, Using the ADO.NET Interface.
For instructions on preparing to use and then defining a native database
interface, see Chapter 7, Using Native Database Interfaces.
12 PowerBuilder
PA RT 2 Working with Standard
Database Interfaces
13
CHAPTER 2 Using the ODBC Interface
About this chapter This chapter gives an introduction to the ODBC interface and then describes
how to prepare to use the data source, how to define the data source, and how
to define the ODBC database profile. It also describes how to use the SAP SQL
Anywhere ODBC driver.
Contents
Topic Page
About the ODBC interface 15
Preparing ODBC data sources 24
Defining ODBC data sources 25
Defining the ODBC interface 29
SAP SQL Anywhere 30
For more information This chapter gives general information about preparing to use and defining
each ODBC data source. For more detailed information, use the online Help
provided by the driver vendor, as described in Displaying Help for ODBC
drivers on page 28. This Help provides important details about using the data
source.
What is ODBC?
The ODBC API Open Database Connectivity (ODBC) is a standard application programming
interface (API) developed by Microsoft. It allows a single application to access
a variety of data sources for which ODBC-compliant drivers exist. The
application uses Structured Query Language (SQL) as the standard data access
language.
16 PowerBuilder
CHAPTER 2 Using the ODBC Interface
Component Table 2-1 gives the provider and a brief description of each ODBC component
descriptions shown in the diagram.
Table 2-1: Provider and function of ODBC connection components
Component Provider What it does
Application SAP Calls ODBC functions to submit SQL
statements, catalog requests, and retrieve results
from a data source.
PowerBuilder uses the same ODBC interface to
access all ODBC data sources.
ODBC Driver Microsoft Installs, loads, and unloads drivers for an
Manager application.
18 PowerBuilder
CHAPTER 2 Using the ODBC Interface
Multiple-tier driver A multiple-tier ODBC driver processes ODBC functions, but sends SQL
statements to the database engine for processing. Unlike the single-tier driver,
a multiple-tier driver does not include the data access software required to
manage the data directly.
An example of a multiple-tier ODBC driver is the SAP SQL Anywhere driver.
20 PowerBuilder
CHAPTER 2 Using the ODBC Interface
22 PowerBuilder
CHAPTER 2 Using the ODBC Interface
24 PowerBuilder
CHAPTER 2 Using the ODBC Interface
Editing In most cases, you do not need to edit PBODB170.INI. In certain situations,
however, you might need to add functions to PBODB170.INI for your
back-end DBMS. Be sure to edit the copy in your user profile folder, not the
original copy.
For instructions, see the Appendix, Adding Functions to the PBODB170
Initialization File.
26 PowerBuilder
CHAPTER 2 Using the ODBC Interface
• Optional description
• DBMS-specific connection parameters
Editing Do not edit the ODBC subkey directly to modify connection information.
Instead, use a tool designed to define ODBC data sources and the ODBC
configuration automatically, such as the ODBC Data Source Administrator.
28 PowerBuilder
CHAPTER 2 Using the ODBC Interface
Name change
For versions 6 through 9, the SQL Anywhere database server was called
Adaptive Server® Anywhere (ASA). However in this documentation, we call
all of them SQL Anywhere for the sake of consistence.
SQL Anywhere includes two database servers—a personal database server and
a network database server. For information about using SAP SQL Anywhere,
see the SQL Anywhere documentation.
30 PowerBuilder
CHAPTER 2 Using the ODBC Interface
To define a SQL Anywhere data source for the SQL Anywhere driver:
1 Select Create ODBC Data Source from the list of ODBC utilities in the
Database Profiles dialog box or the Database painter.
2 Select User Data Source and click Next.
32 PowerBuilder
CHAPTER 2 Using the ODBC Interface
3 On the Create New Data Source page, select the SQL Anywhere driver
and click Finish.
The ODBC Configuration for SQL Anywhere dialog box displays:
Specify one of the following commands in the Start Line field on the Database
tab page, where n is the version of SQL Anywhere you are using.
Specify this command To
dbengn.exe Start the personal database server and the database
specified in the Database File box
rtengn.exe Start the restricted runtime database server and the
database specified in the Database File box
34 PowerBuilder
CHAPTER 2 Using the ODBC Interface
3 If you are working with the table in the Data Pipeline painter, select the
initial value exclude for the special timestamp column from the drop-down
list in the Initial Value column of the workspace.
You must select exclude as the initial value to exclude the special
timestamp column from INSERT or UPDATE statements.
For instructions, see the Users Guide.
CREATE TABLE The following CREATE TABLE statement defines a SQL Anywhere table
example named timesheet containing three columns: employee_ID (integer datatype),
hours (decimal datatype), and timestamp (timestamp datatype and timestamp
default value):
CREATE TABLE timesheet (
employee_ID INTEGER,
hours DECIMAL,
timestamp TIMESTAMP default timestamp )
Not using special If you want to change the default behavior, you can specify that PowerBuilder
timestamp columns not treat SQL Anywhere columns named timestamp as Transact-SQL special
timestamp columns.
What to do next
For instructions on connecting to the ODBC data source, see Connecting to a
database on page 169.
36 PowerBuilder
CHAPTER 3 Using the JDBC Interface
About this chapter This chapter describes the JDBC interface and explains how to prepare to use
this interface and how to define the JDBC database profile.
Contents
Topic Page
About the JDBC interface 37
Preparing to use the JDBC interface 41
Defining the JDBC interface 43
For more information For more detailed information about JDBC, go to the Java Web site at
http://java.sun.com/products/jdbc/overview.html.
What is JDBC?
The JDBC API Java Database Connectivity (JDBC) is a standard application programming
interface (API) that allows a Java application to access any database that
supports Structured Query Language (SQL) as its standard data access
language.
The JDBC API includes classes for common SQL database activities that allow
you to open connections to databases, execute SQL commands, and process
results. Consequently, Java programs have the capability to use the familiar
SQL programming model of issuing SQL statements and processing the
resulting data. The JDBC classes are included in Java 1.1+ and Java 2 as the
java.sql package.
38 PowerBuilder
CHAPTER 3 Using the JDBC Interface
The JDBC DLL PowerBuilder provides the pbjdb170.dll. This DLL runs with the Sun Java
Runtime Environment (JRE) versions 1.1 and later.
PowerBuilder Java PowerBuilder includes a small package of Java classes that gives the JDBC
package interface the level of error-checking and efficiency (SQLException catching)
found in other PowerBuilder interfaces. The package is called pbjdbc12170.jar
and is found in Appeon\Shared\PowerBuilder.
The Java Virtual The Java Virtual Machine (JVM) is a component of Java development
Machine software. When you install PowerBuilder, the Sun Java Development Kit
(JDK), including the Java Runtime Environment (JRE), is installed on your
system in Appeon\Shared\PowerBuilder. For PowerBuilder 17.0, JDK 1.6 is
installed. This version of the JVM is started when you use a JDBC connection
or any other process that requires a JVM and is used throughout the
PowerBuilder session.
If you need to use a different JVM, see the instructions in Preparing to use the
JDBC interface on page 41. For more information about how the JVM is
started, see the chapter on deploying your application in Application
Techniques.
The JDBC drivers The JDBC interface can communicate with any JDBC-compliant driver
including SAP jConnect™ for JDBC (available with SAP ASE, IQ, and SA
database clients) and the Oracle and IBM Informix JDBC drivers. These
drivers are native-protocol, all-Java drivers—that is, they convert JDBC calls
into the SQL syntax supported by the databases.
Accessing Unicode Using the ODBC interface, PowerBuilder can connect, save, and retrieve data
data in both ANSI/DBCS and Unicode databases but does not convert data between
Unicode and ANSI/DBCS. When character data or command text is sent to the
database, PowerBuilder sends a Unicode string. The driver must guarantee that
the data is saved as Unicode data correctly. When PowerBuilder retrieves
character data, it assumes the data is Unicode.
A Unicode database is a database whose character set is set to a Unicode
format, such as UTF-8, UTF-16, UCS-2, or UCS-4. All data must be in
Unicode format, and any data saved to the database must be converted to
Unicode data implicitly or explicitly.
A database that uses ANSI (or DBCS) as its character set might use special
datatypes to store Unicode data. Columns with these datatypes can store only
Unicode data. Any data saved into such a column must be converted to
Unicode explicitly. This conversion must be handled by the database server or
client.
40 PowerBuilder
CHAPTER 3 Using the JDBC Interface
42 PowerBuilder
CHAPTER 3 Using the JDBC Interface
For more information about configuring jConnect, see the jConnect for JDBC
documentation.
44 PowerBuilder
CHAPTER 4 Using the OLE DB Interface
About this chapter This chapter describes the OLE DB interface and explains how to prepare to
use this interface and how to define the OLE DB database profile.
Contents
Topic Page
About the OLE DB interface 45
Preparing to use the OLE DB interface 49
Defining the OLE DB interface 51
For more information This chapter gives general information about using the OLE DB interface. For
more detailed information:
• See the OLE DB Programmer’s Guide in the Microsoft MSDN library at
http://msdn.microsoft.com/en-us/library/ms713643.aspx.
46 PowerBuilder
CHAPTER 4 Using the OLE DB Interface
Accessing Unicode Using the OLE DB interface, PowerBuilder can connect, save, and retrieve
data data in both ANSI/DBCS and Unicode databases but does not convert data
between Unicode and ANSI/DBCS. When character data or command text is
sent to the database, PowerBuilder sends a Unicode string. The data provider
must guarantee that the data is saved as Unicode data correctly. When
PowerBuilder retrieves character data, it assumes the data is Unicode.
A Unicode database is a database whose character set is set to a Unicode
format, such as UTF-8, UTF-16, UCS-2, or UCS-4. All data must be in
Unicode format, and any data saved to the database must be converted to
Unicode data implicitly or explicitly.
A database that uses ANSI (or DBCS) as its character set might use special
datatypes to store Unicode data. Columns with these datatypes can store only
Unicode data. Any data saved into such a column must be converted to
Unicode explicitly. This conversion must be handled by the database server or
client.
48 PowerBuilder
CHAPTER 4 Using the OLE DB Interface
Step 1: Install and You must install and configure the database server and install the network
configure the data software and client software.
server
Step 2: Install the OLE In the PowerBuilder Setup program, select the Custom install and select the
DB interface and data OLE DB provider that accesses your database. You can install one or more of
provider
the OLE DB data providers shipped with PowerBuilder, or you can install data
providers from another vendor later.
Step 3: Install the The PowerBuilder OLE DB interface requires the functionality of the
Microsoft Data Access Microsoft Data Access Components (MDAC) version 2.8 or higher software.
Components software
To check the version of MDAC on your computer, you can download and run
the MDAC Component Checker utility from the MDAC Downloads page at
http://msdn.microsoft.com/en-us/data/aa937730.aspx.
50 PowerBuilder
CHAPTER 4 Using the OLE DB Interface
Step 4: Define the Once the OLE DB data provider is installed, you might have to define the OLE
OLE DB data source DB data source the data provider will access. How you define the data source
depends on the OLE DB data provider you are using and the vendor who
provided it.
If you are connecting to an ODBC data provider (such as Microsoft’s OLE DB
Provider for ODBC), you must define the ODBC data source as you would if
you were using a direct ODBC connection. To define an ODBC data source,
use Microsoft’s ODBC Data Source Administrator. You can access this utility
from the Control Panel in Windows or from the Database painter or Database
Profile Setup dialog box in PowerBuilder.
Using the Data Link The Data Link option allows you to access Microsoft’s Data Link API, which
API allows you to define a file or use an existing file that contains your OLE DB
connection information. A Data Link file is identified with the suffix .udl. If
you use a Data Link file to connect to your data source, all other settings you
make in the OLE DB Database Profile Setup dialog box are ignored.
To launch this option, select the File Name check box on the Connection tab
and double-click on the button next to the File Name box. (You can also launch
the Data Link API in the Database painter by double-clicking on the Manage
Data Links utility included with the OLE DB interface in the list of Installed
Database Interfaces.)
For more information on using the Data Link API, see the OLE DB
Programmer’s Guide in the Microsoft MSDN library at
http://msdn.microsoft.com/en-us/library/ms713643.aspx.
52 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
About this chapter This chapter describes the ADO.NET interface and explains how to prepare to
use this interface and how to define an ADO.NET database profile.
Contents
Topic Page
About ADO.NET 53
About the PowerBuilder ADO.NET database interface 54
Preparing to use the ADO.NET interface 58
Defining the ADO.NET interface 60
Sharing ADO.NET Database Connections 64
For more information This chapter gives general information about using the ADO.NET interface.
For more detailed information:
• See the Data Access and .NET development sections in the Microsoft
MSDN library at http://msdn.microsoft.com/en-us/data/default.aspx.
About ADO.NET
ADO.NET is a set of technologies that provides native access to data in the
Microsoft .NET Framework. It is designed to support an n-tier programming
environment and to handle a disconnected data architecture. ADO.NET is
tightly integrated with XML and uses a common data representation that can
combine data from disparate sources, including XML.
One of the major components of ADO.NET is the .NET Framework data
provider, which connects to a database, executes commands, and retrieves
results.
Microsoft provides .NET Framework data providers for SQL Server and OLE
DB with the .NET Framework, and data providers for ODBC and Oracle can
be downloaded from the Microsoft Web site. You can also obtain .NET
Framework data providers from other vendors, such as the .NET Framework
Data Provider for Adaptive Server Enterprise from SAP.
To connect to a database using the PowerBuilder ADO.NET database
interface, you must use a .NET Framework data provider.
Accessing Unicode Using the ADO.NET interface, PowerBuilder can connect, save, and retrieve
data data in both ANSI/DBCS and Unicode databases but does not convert data
between Unicode and ANSI/DBCS. When character data or command text is
sent to the database, PowerBuilder sends a Unicode string. The data provider
must guarantee that the data is saved as Unicode data correctly. When
PowerBuilder retrieves character data, it assumes the data is Unicode.
A Unicode database is a database whose character set is set to a Unicode
format, such as UTF-8, UTF-16, UCS-2, or UCS-4. All data must be in
Unicode format, and any data saved to the database must be converted to
Unicode data implicitly or explicitly.
A database that uses ANSI (or DBCS) as its character set might use special
datatypes to store Unicode data. Columns with these datatypes can store only
Unicode data. Any data saved into such a column must be converted to
Unicode explicitly. This conversion must be handled by the database server or
client.
Performance
You might experience better performance if you use a native database
interface. The primary purpose of the ADO.NET interface is to support shared
connections with other database constructs such as the .NET DataGrid in SAP
DataWindow .NET.
54 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
56 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
58 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
Step 1: Install and You must install and configure the database server and install the network
configure the data software and client software.
server
Step 2: Install the In the PowerBuilder Setup program, select the Custom install and select the
ADO.NET interface ADO.NET database interface.
Step 3: Install the The PowerBuilder ADO.NET interface requires the functionality of the
Microsoft Data Access Microsoft Data Access Components (MDAC) version 2.8 or higher software.
Components software
To check the version of MDAC on your computer, you can download and run
the MDAC Component Checker utility from the MDAC Downloads page at
http://msdn.microsoft.com/en-us/data/aa937730.aspx.
60 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
<dbConfiguration>
<mycustomconfig dbParm="optional_value"
getIdentity="optional_syntax"
/>
</dbConfiguration>
</configuration>
<runtime>
<assemblyBinding xmlns=
"urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name=
"Sybase.PowerBuilder.Db"/>
<codeBase href="file:///C:/Program Files/
Appeon/PowerBuilder 17.0/DotNET/bin/
62 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
Sybase.PowerBuilder.Db.dll"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=
"Sybase.PowerBuilder.WebService.WSDL"/>
<codeBase href="file:///C:/Program Files/
Appeon/PowerBuilder 17.0/DotNET/bin/
Sybase.PowerBuilder.WebService.WSDL.dll"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=
"Sybase.PowerBuilder.WebService.Runtime"/>
<codeBase href="file:///C:/Program Files/
Appeon/PowerBuilder 17.0/DotNET/bin/
Sybase.PowerBuilder.WebService.
Runtime.dll"/>
</dependentAssembly>
<probing privatePath="DotNET/bin" />
</assemblyBinding>
</runtime>
<dbConfiguration>
<myconfig dbParm="disablebind=1"
getIdentity="select scope_identity()"
/>
<myconfig1 getIdentity="select scope_identity()"
/>
<myconfig2 dbParm=
"Namespace='Oracle.DataAccess.Client',
DataSource='ora10gen',DisableBind=1,
NCharBind=1,ADORelease='10.1.0.301'"
/>
</dbConfiguration>
</configuration>
Specifying the custom On the System tab page in the Database Profile Setup dialog box for ADO.NET
configuration to be or in code, specify the name of the custom configuration section you want to
used
use as the value of the DbConfigSection parameter. For example:
Sqlca.DBParm="DbConfigSection='myconfig'"
If you set any parameters in the profile or in code that are also set in the
configuration file, the value specified in the configuration file takes
precedence.
The configuration file must be present in the same directory as the executable
file and must have the same name with the extension .config.
64 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
The method returns true if the parameter is available (that is, the parameter is
an instance of IAdoConnectionProxy or null). It returns false if the operation
fails.
Start the connection after invoking SetAdoConnection.
Sample PowerScript //Sample PowerScript code
Code SQLCA.DBMS = "ADO.NET"
SQLCA.AutoCommit = true
SQLCA.DBParm = "Namespace='System.Data.Odbc', DataSource='SQL
Anywhere 11 Demo'"
bool retVal = SQLCA.SetAdoConnection(emp.AdoConnectionProxy)
// emp is an instance of a type in the 3rd-party .NET assembly
if (retVal = true) then
connect using SQLCA;
// db operations
end if
66 PowerBuilder
CHAPTER 5 Using the ADO.NET Interface
The method returns null if the connection fails, and false if the operation fails.
To use the shared connection, your third-party assembly must reference the
exported connection proxy and manage the transaction. To be notified when
the active transaction is changed, you can subscribe the
IAdoConnection.TransactionChanged event . Remember to close the
connection.
Sample PowerScript //Sample PowerScript code
Code SQLCA.DBMS = "ADO.NET"
SQLCA.AutoCommit = false
SQLCA.DBParm = "Namespace='System.Data.Odbc', DataSource='SQL
Anywhere 11 Demo'"
Connect Using SQLCA;
emp.ConnectionProxy = SQLCA.GetAdoConnection()
// db operations
disconnect using SQLCA;
68 PowerBuilder
CHAPTER 6 Using the OData Interface
About this chapter This chapter describes the OData interface and explains how to prepare to use
this interface and how to define the OData database profile.
PowerBuilder can use OData datasources.
OData (the Open Data Protocol) is a Web protocol for querying and updating
data that provides a way to unlock your data and free it from silos that exist in
applications. OData is based on REST (Representational State Transfer). It
uses the standard HTTP protocol to access data using GET, PUT, POST, and
DELETE.
At runtime, users can retrieve and manipulate data.
Contents
Topic Page
Database Profile Setup - OData Dialog Box 69
Database Painter 71
Create a DataWindow Using an OData Service 72
Set the Connection Information for the OData Service 72
Connection Tab
The Connection tab includes basic connection options that you must supply to
access the information in the OData service.
• Profile Name The name of your database profile.
• Connection Information The uniform resource identifier (URI) that
represents the OData service.
Certificate Tab
The Certificate tab includes basic connection options that you must supply to
access the information in the OData service.
Select one connection option:
• No X509 Certificate Select this option when the OData service does not
require a certificate.
• Select a certificate from current user's personal store Click Change
to select a certificate.
• Specify a local certificate file Click Browse to select a certificate file
on the local machine.
70 PowerBuilder
CHAPTER 6 Using the OData Interface
• Bypass proxy server for local addresses Use this option to bypass
the proxy server when the OData Service is using a local address.
Preview Tab
The Preview tab provides a convenient way to generate correct PowerScript
connection syntax in the PowerBuilder development environment for use in
your PowerBuilder application script.
As you complete the Database Profile Setup dialog box for OData, the correct
PowerScript connection syntax for each select option is built on the Preview
tab. You can then copy the syntax you want from the Preview tab into your
PowerBuilder application script.
• Copy Copies the selected text in the Database Connection Syntax box to
the clipboard. You can then paste the syntax into your PowerBuilder script.
Database Painter
You can connect to the OData service and work with it in the Database painter.
The Database painter supports these features:
• Define an OData datasource with the database profile painter.
• Connect to an OData datasource in the Objects view.
• Add tables to the Object Layout view with drag-and-drop or the context
menu.
• Display table and column properties in the Properties view with drag-and-
drop or the context menu.
• Drag and drop a table onto the Columns view.
• Invoke the Edit Data feature in the Results view of the Database painter.
Since OData is not a SQL source, some features are not supported:
• The ISQL Session view is not enabled.
• You cannot create, modify, or delete tables.
• You cannot create users or groups of users.
72 PowerBuilder
CHAPTER 6 Using the OData Interface
74 PowerBuilder
PA RT 3 Working with Native
Database Interfaces
75
CHAPTER 7 Using Native Database Interfaces
About this chapter This chapter describes native database interfaces. The following chapters
explain how to prepare to use the database and define any unique database
interface parameters so that you can access your data.
Contents
Topic Page
About native database interfaces 77
Components of a database interface connection 78
Using a native database interface 79
78 PowerBuilder
CHAPTER 7 Using Native Database Interfaces
For diagrams showing the specific components of your connection, see “Basic
software components” in the chapter for your native database interface.
About installing native After you prepare to use the database, you must install the native database
database interfaces interface that accesses the database. See the instructions for each interface for
more information.
About defining native Once you are ready to access the database, you start PowerBuilder and define
database interfaces the database interface. To define a database interface, you must create a
database profile by completing the Database Profile Setup dialog box for that
interface.
For general instructions, see About creating database profiles on page 7. For
instructions about defining database interface parameters unique to a particular
database, see “Preparing to use the database” in the chapter for your database
interface.
For more information The following chapters give general information about using each native
database interface. For more detailed information:
• Check to see if there is a technical document that describes how to connect
to your database.
• Ask your network or system administrator for assistance when installing
and setting up the database server and client software at your site.
80 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
About this chapter This section describes how to use the Adaptive Server Enterprise database
interfaces in PowerBuilder.
Contents
Topic Page
Supported versions for Adaptive Server 81
Supported Adaptive Server datatypes 82
Basic software components for Adaptive Server 85
Preparing to use the Adaptive Server database 86
Defining the Adaptive Server database interface 88
Using Open Client security services 89
Using Open Client directory services 91
Using PRINT statements in Adaptive Server stored procedures 95
Creating a report based on a cross-database join 95
Installing stored procedures in Adaptive Server databases 95
82 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
Accessing Unicode PowerBuilder can connect, save, and retrieve data in both ANSI/DBCS and
data Unicode databases. When character data or command text is sent to the
database, PowerBuilder sends a DBCS string if the UTF8 database parameter
is set to 0 (the default). If UTF8 is set to 1, PowerBuilder sends a UTF-8 string.
The database server must be configured correctly to accept UTF-8 strings. See
the description of the UTF8 database parameter in the online Help for more
information.
The character set used by an Adaptive Server database server applies to all
databases on that server. The nchar and nvarchar datatypes can store UTF-8
data if the server character set is UTF-8. The Unicode datatypes unichar and
univarchar were introduced in Adaptive Server 12.5 to support Unicode data.
Columns with these datatypes can store only Unicode data. Any data saved into
such a column must be converted to Unicode explicitly. This conversion must
be handled by the database server or client.
In Adaptive Server 12.5.1 and later, additional support for Unicode data has
been added. For more information, see the documentation for your version of
Adaptive Server.
Different display The unichar and univarchar datatypes support UTF-16 encoding, therefore
values in painters each unichar or univarchar character requires two bytes of storage. The
following example creates a table with one unichar column holding 10 Unicode
characters:
create table unitbl (unicol unichar(10))
In the Database painter, the column displays as unichar(20)because the
column requires 20 bytes of storage. This is consistent with the way the column
displays in SAP Central.
However, the mapping between the Type in the Column Specifications view in
the Report painter and the column datatype of a table in the database is not one-
to-one. The Type in the Column Specifications view shows the DataWindow®
column datatype and DataWindow column length. The column length is the
number of characters, therefore an Adaptive Server unichar(20)column
displays as char(10) in the Column Specifications view.
Column-length limits Adaptive Server 12.5 and earlier have a column-length limit of 255 bytes.
Adaptive Server 12.5.x and later support wider columns for Char, VarChar,
Binary, and VarBinary datatypes, depending on the logical page size and the
locking scheme used by the server.
In PowerBuilder, you can use these wider columns for Char and VarChar
datatypes with Adaptive Server 12.5.x when the following conditions apply:
• The Release database parameter is set to 12.5 or higher.
• You are accessing the database using Open Client 12.5.x or later.
The database must be configured to use a larger page size to take full advantage
of the widest limits.
For more information about the Release database parameter, see “Release
database parameter”.
When you retrieve or update columns, PowerBuilder converts data
appropriately between the Adaptive Server datatype and the PowerScript
datatype. Similarly or identically named Adaptive Server and PowerScript
datatypes do not necessarily have the same definitions. For information about
the definitions of PowerScript datatypes, see the PowerScript Reference.
Conversion in A double that has no fractional component is converted to a string with one
PowerBuilder scripts decimal place if the converted string would cause Adaptive Server to have an
overflow error when parsing the string. For example: the double value
12345678901234 would cause an overflow error, so PowerBuilder converts the
double to the string value 12345678901234.0.
84 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
86 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
4 Make sure the Open Client software is properly configured so that you can
connect to the database at your site.
Installing the Open Client software places the SQL.INI configuration file
in the Adaptive Server directory on your computer.
SQL.INI provides information that Adaptive Server needs to find and
connect to the database server at your site. You can enter and modify
information in SQL.INI by using the configuration utility that comes with
the Open Client software.
For information about setting up the SQL.INI or other required
configuration file, see your Adaptive Server documentation.
5 If required by your operating system, make sure the directory containing
the Open Client software is in your system path.
6 Make sure only one copy of each of the following files is installed on your
client computer:
• Adaptive Server interface DLL
• Network communication DLL (for example, NLWNSCK.DLL for
Windows Sockets-compliant TCP/IP)
• Database vendor DLL (for example, LIBCT.DLL)
Step 2: Install the In the PowerBuilder Setup program, select the Typical install, or select the
database interface Custom install and select the Adaptive Server Enterprise (ASE or SYC)
database interface.
Step 3: Verify the Make sure you can connect to the Adaptive Server database server and log in
connection to the database you want to access from outside PowerBuilder.
Some possible ways to verify the connection are by running the following
tools:
• Accessing the database server Tools such as the Open Client/Open
Server Configuration utility (or any Ping utility) check whether you can
reach the database server from your computer.
• Accessing the database Tools such as ISQL (interactive SQL utility)
check whether you can log in to the database and perform database
operations. It is a good idea to specify the same connection parameters you
plan to use in your PowerBuilder database profile to access the database.
Step 4: Install the PowerBuilder requires you to install certain stored procedures in the
PowerBuilder stored sybsystemprocs database before you connect to an Adaptive Server database
procedures
for the first time. PowerBuilder uses these stored procedures to get information
about tables and columns from the DBMS system catalog.
Run the SQL script or scripts required to install the PowerBuilder stored
procedures in the sybsystemprocs database.
For instructions, see Installing stored procedures in Adaptive Server databases
on page 95.
88 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
90 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
Sec_Sess_Timeout
For instructions on setting these DBParm parameters, see their descriptions in
the online Help.
Per-packet security The following per-packet security DBParm parameters correspond to Open
DBParms Client 11.1.x or later connection properties that protect each packet of data
transmitted across a network. Using per-packet security services might create
extra overhead for communications between the client and server.
Sec_Confidential
Sec_Data_Integrity
Sec_Data_Origin
Sec_Replay_Detection
Sec_Seq_Detection
For instructions on setting these DBParm parameters, see their descriptions in
the online Help.
92 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
94 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
Where to find the The stored procedure scripts are located in the Server directory on the
scripts PowerBuilder installation package. The Server directory contains server-side
installation components that are not installed with PowerBuilder on your
computer.
PBSYC.SQL script
What it does The PBSYC.SQL script contains SQL code that overwrites stored procedures
that correspond to the same version of PowerBuilder in the Adaptive Server
sybsystemprocs database and then re-creates them.
The PBSYC.SQL script uses the sybsystemprocs database to hold the
PowerBuilder stored procedures. This database is created when you install
Adaptive Server.
96 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
When to run it Before you connect to an Adaptive Server database in PowerBuilder for the
first time using the ASE or SYC DBMS identifier, you or your database
administrator must run the PBSYC.SQL script once per database server into the
sybsystemprocs database.
Run PBSYC.SQL if the server at your site will be accessed by anyone using the
PowerBuilder or by deployment machines.
If you or your database administrator have already run the current version of
PBSYC.SQL to install PowerBuilder stored procedures in the sybsystemprocs
database on your server, you need not rerun the script to install the stored
procedures again.
For instructions on running PBSYC.SQL, see How to run the scripts on page
99.
Stored procedures it The PBSYC.SQL script creates the following PowerBuilder stored procedures
creates in the Adaptive Server sybsystemprocs database. The procedures are listed in
the order in which the script creates them.
PBSYC.SQL
stored
procedure What it does
sp_pb170column Lists the columns in a table.
sp_pb170pkcheck Determines whether a table has a primary key.
sp_pb170fktable Lists the tables that reference the current table.
sp_pb170procdesc Retrieves a description of the argument list for a specified
stored procedure.
sp_pb170proclist Lists available stored procedures and extended stored
procedures.
If the SystemProcs DBParm parameter is set to 1 or Yes (the
default), sp_pb170proclist displays both system stored
procedures and user-defined stored procedures. If SystemProcs
is set to 0 or No, sp_pb170proclist displays only user-defined
stored procedures.
sp_pb170text Retrieves the text of a stored procedure from the
SYSCOMMENTS table.
sp_pb170table Retrieves information about all tables in a database, including
those for which the current user has no permissions.
PBSYC.SQL contains the default version of sp_pb170table. If
you want to replace the default version of sp_pb170table with
a version that restricts the table list to those tables for which the
user has SELECT permission, you can run the PBSYC2.SQL
script, described in PBSYC2.SQL script next.
sp_pb170index Retrieves information about all indexes for a specified table.
PBSYC2.SQL script
What it does The PBSYC2.SQL script contains SQL code that drops and re-creates one
PowerBuilder stored procedure in the Adaptive Server sybsystemprocs
database: a replacement version of sp_pb170table.
The default version of sp_pb170table is installed by the PBSYC.SQL script.
PowerBuilder uses the sp_pb170table procedure to build a list of all tables in
the database, including those for which the current user has no permissions.
This list displays in the Select Tables dialog box in PowerBuilder.
For security reasons, you or your database administrator might want to restrict
the table list to display only those tables for which a user has permissions. To
do this, you can run the PBSYC2.SQL script after you run PBSYC.SQL.
PBSYC2.SQL replaces the default version of sp_pb170table with a new version
that displays a restricted table list including only tables and views:
• Owned by the current user
• For which the current user has SELECT authority
• For which the current user’s group has SELECT authority
• For which SELECT authority was granted to PUBLIC
When to run it If you are accessing an Adaptive Server database using the ASE or SYC
DBMS identifier in PowerBuilder, you must first run PBSYC.SQL once per
database server to install the required PowerBuilder stored procedures in the
sybsystemprocs database.
After you run PBSYC.SQL, you can optionally run PBSYC2.SQL if you want
to replace sp_pb170table with a version that restricts the table list to those
tables for which the user has SELECT permission.
If you do not want to restrict the table list, there is no need to run PBSYC2.SQL.
For instructions on running PBSYC2.SQL, see How to run the scripts on page
99.
Stored procedure it The PBSYC2.SQL script creates the following PowerBuilder stored procedure
creates in the Adaptive Server sybsystemprocs database:
PBSYC2.SQL
stored procedure What it does
sp_pb170table Retrieves information about those tables in the database
for which the current user has SELECT permission.
This version of sp_pb170table replaces the default version
of sp_pb170table installed by the PBSYC.SQL script.
98 PowerBuilder
CHAPTER 8 Using Adaptive Server Enterprise
For example, if you are using PowerBuilder and are accessing the stored
procedure scripts from d:\server, type either of the following:
isql /U sa /S TESTDB /i d:\server\pbsyb.sql /P
isql /U sa /S SALES /i d:\server\pbsyc.sql /P
adminpwd
100 PowerBuilder
CHAPTER 9 Using Informix
C HA P T E R 9 Using Informix
About this chapter This chapter describes how to use the native IBM Informix database interfaces
in PowerBuilder.
Contents
Topic Page
Supported versions for Informix 101
Supported Informix datatypes 101
Features supported by the I10 interface 103
Basic software components for Informix 108
Preparing to use the Informix database 109
Defining the Informix database interface 110
Accessing serial values in a PowerBuilder script 112
Boolean Money
Byte (a maximum of 2^31 bytes) NChar
Char NVarChar
Clob Real
Date Serial
DateTime Serial8
Decimal SmallInt (2 bytes)
Float Text (a maximum of 2^31 bytes)
Int8 Time
Integer (4 bytes) VarChar (1 to 255 bytes)
Interval
Datatype conversion
When you retrieve or update columns, PowerBuilder converts data
appropriately between the Informix datatype and the PowerScript datatype.
Keep in mind, however, that similarly or identically named Informix and
PowerScript datatypes do not necessarily have the same definitions.
For information about the definitions of PowerScript datatypes, see the
PowerScript Reference.
102 PowerBuilder
CHAPTER 9 Using Informix
The Columns view displays the pending changes to the table definition.
These changes execute only when you click the Save button to save the
table definition.
3 Select Copy from the Edit or pop-up menu or click the Copy button.
The SQL syntax (or the portion you selected) is copied to the clipboard.
4 In the ISQL view, modify the DateTime syntax and execute the CREATE
TABLE statement.
For instructions on using the ISQL view, see the Users Guide.
104 PowerBuilder
CHAPTER 9 Using Informix
Renaming an index
With IDS 9.2.1 and later, you can change the name of an index in the Database
painter when you are connected using the I10 interface. The I10 interface uses
the IDS RENAME INDEX statement to change the name of the index. You
need only drop and recreate the index if you want to make other changes.
You can set the StmtCache DBParm on the System tab page in the Database
Profile Setup dialog box for I10 connections to turn SQL statement caching on
or off on the client. However, the server must be configured to support SQL
statement caching before you can access the cache from the client.
For more information about Informix SQL statement caching, see the IBM
Informix Dynamic Server Performance Guide at
http://publib.boulder.ibm.com/infocenter/idshelp/v111/index.jsp?topic=/com.ibm.gl
sug.doc/glsug.htm.
106 PowerBuilder
CHAPTER 9 Using Informix
You can set the OnlineIndex static DBParm on the System tab page in the
Database Profile Setup dialog box for I10 connections to specify that the
Database painter should use the ONLINE keyword when you create or drop an
index.
Column-level encryption
In IDS 10.0 and later, the SQL statement SET ENCRYPTION PASSWORD can
improve the confidentiality of data and support data integrity by defining or
resetting a password for encryption and decryption of data at the column level.
You can set the EncryptionPass and Hint static DBParms on the System tab
page in the Database Profile Setup dialog box for I10 connections to specify a
password and a hint to help you remember the password. The application uses
built-in Informix functions to encrypt and decrypt character data.
Informix does not support invoking a UDR with OUT parameters using an
EXECUTE statement, therefore multiple OUT parameters are not supported in
PowerBuilder remote procedure calls and embedded SQL EXECUTE
PROCEDURE commands.
108 PowerBuilder
CHAPTER 9 Using Informix
To install and configure the required database server, network, and client
software:
1 Make sure the Informix database server software and database network
software is installed and running on the server specified in your database
profile.
You must obtain the database server and database network software from
Informix.
For installation instructions, see your Informix documentation.
2 Install the required Informix client software on each client computer on
which PowerBuilder is installed.
Install Informix Connect or the Informix Client SDK (which includes
Informix Connect).
You must obtain the Informix client software from IBM. Make sure the
version of the client software you install supports all of the following:
The operating system running on the client computer
The version of the database that you want to access
The version of PowerBuilder that you are running
For installation instructions, see your Informix documentation.
3 Make sure the Informix client software is properly configured so that you
can connect to the Informix database server at your site.
Run the SetNet32 utility to configure the client registry settings. When you
configure Informix Connect client software, it creates a registry entry in
HKEY_LOCAL_MACHINE\Software\Informix\SqlHosts. The registry
entry contains parameters that define your network configuration, network
protocol, and environment variables. If you omit these values from the
database profile when you define the native Informix database interface,
they default to the values specified in the registry entry.
For instructions on configuring your Informix client software, see your
Informix documentation.
4 If required by your operating system, make sure the directory containing
the Informix client software is in your system path.
Step 2: Install the In the PowerBuilder Setup program, select the Typical install, or select the
database interface native Informix database interface in the Custom install.
Step 3: Verify the Make sure you can connect to the Informix server and database you want to
connection access from outside PowerBuilder.
To verify the connection, use any Windows-based utility (such as the Informix
ilogin.exe program) that connects to the database. When connecting, be sure to
specify the same parameters you plan to use in your PowerBuilder database
profile to access the database.
For instructions on using ilogin.exe, see your Informix documentation.
110 PowerBuilder
CHAPTER 9 Using Informix
Tip
If you specify a value for Host Name and Server in your database profile,
this syntax displays on the Preview tab in the Database Profile Setup
dialog box. You can then copy the syntax from the Preview tab into your
script.
112 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
About this chapter This chapter describes how to use the Microsoft SQL Server Native Client
database interface in PowerBuilder.
Contents
Topic Page
Supported versions for SQL Server 113
Supported SQL Server datatypes 114
Basic software components for Microsoft SQL Server 115
Preparing to use the SQL Server database 117
Defining the SQL Server database interface 118
Migrating from the MSS or OLE DB database interfaces 119
SQL Server 2008 features 122
Notes on using the SNC interface 130
The XML datatype is a built-in datatype in SQL Server 2005 that enables you
to store XML documents and fragments in a SQL Server database. The XML
datatype maps to the PowerScript String datatype. You can use this datatype as
a column type when you create a table, as a variable, parameter, or function
return type, and with CAST and CONVERT functions.
Additional datatypes are supported for SQL Server 2008. For more
information, see Support for new datatypes in SQL Server 2008 on page 123.
Datatype conversion
When you retrieve or update columns, PowerBuilder converts data
appropriately between the Microsoft SQL Server datatype and the PowerScript
datatype. Keep in mind, however, that similarly or identically named SQL
Server and PowerScript datatypes do not necessarily have the same definitions.
For information about the definitions of PowerScript datatypes, see the
PowerScript Reference.
114 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
116 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
2 If you are accessing a remote SQL Server database, make sure the required
network software (for example, TCP/IP) is installed and running on your
computer and is properly configured so that you can connect to the SQL
Server database server at your site.
For installation and configuration instructions, see your network or
database administrator.
3 Install the required Microsoft SQL Native Client software on each client
computer on which PowerBuilder is installed.
You must obtain the SQL Native Client software from Microsoft. Make
sure the version of the client software you install supports all of the
following:
The operating system running on the client computer
The version of the database that you want to access
The version of PowerBuilder that you are running
For installation instructions, see your Microsoft SQL Server
documentation.
4 Make sure the SQL Native Client client software is properly configured so
that you can connect to the SQL Server database server at your site.
For configuration instructions, see your Microsoft SQL Server
documentation.
5 Make sure the directory containing the SQL Native Client software is in
your system path.
6 Make sure only one copy of the Sqlncli.dll file is installed on your
computer.
Step 2: Install the In the PowerBuilder Setup program, select the Custom install and select the
database interface SQL Native Client database interface.
Step 3: Verify the Make sure you can connect to the SQL Server server and database you want to
connection access from outside PowerBuilder.
To verify the connection, use any Windows-based utility that connects to the
database. When connecting, be sure to specify the same parameters you plan to
use in your PowerBuilder database profile to access the database.
118 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
MSS SNC
Log Not supported
SystemProcs Not supported
PBCatalogOwner Supported
Transaction tab:
Async Not supported
DBGetTime Not supported
CursorLock Not supported
CursorScroll Not supported
StaticBind Supported
MaxConnect Not supported
Syntax tab:
DBTextLimit Supported (as PBMaxTextSize on Transaction tab)
DateTimeAllowed Not supported
OptSelectBlob Not supported
Network tab:
AppName Supported (System tab)
Host Supported (System tab)
PacketSize Supported (System tab)
Secure Supported (as TrustedConnection on General tab)
OLE DB database Table 10-3 shows the database parameters and preferences that can be set in the
parameters supported Database Profile Setup dialog box for the OLE DB standard interface for
by SNC
Microsoft SQL Server, and indicates whether they are supported by the SNC
interface.
The column on the left shows the tab page in the Database Profile Setup dialog
box for OLE DB. The parameters and preferences may be on different tab
pages in the SNC profile.
Table 10-3: OLE DB parameters supported by SNC
OLE DB SNC
Connection tab:
Provider Not supported
DataSource Supported at runtime (as SQLCA.ServerName)
DataLink Supported
Location Not supported
ProviderString Supported
System tab:
PBCatalogOwner Supported
120 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
OLE DB SNC
ServiceComponents Not supported
AutoCommit Supported (General tab)
CommitOnDisconnect Supported (General tab)
StaticBind Supported (Transaction tab)
DisableBind Supported (Transaction tab)
Init_Prompt Not supported
TimeOut Supported
LCID Not supported
Transaction tab:
Block Supported
PBMaxBlobSize Supported
Mode Not supported
Lock Supported
Syntax tab:
DelimitIdentifier Supported
IdentifierQuoteChar Not supported
DateFormat Supported
TimeFormat Supported
DecimalSeparator Supported
OJSyntax Supported
Security tab:
EncryptPassword Not supported
CacheAuthentication Not supported
PersistSensitive Not supported
MaskPassword Not supported
PersistEncrypted Not supported
IntegratedSecurity Supported (TrustedConnection on General tab)
ImpersonationLevel Not supported
ProtectionLevel Not supported
Additional database The SNC interface also supports the ReCheckRows and BinTxtBlob
parameters runtime-only parameters, the Encrypt, TrustServerCertificate, and SPCache
parameters (on the System tab page), and the Identity parameter (on the Syntax
tab page).
SPCache database You can control how many stored procedures are cached with parameter
parameter information by modifying the setting of the SPCache database parameter. The
default is 100 procedures. To turn off caching of stored procedures, set
SPCache to 0.
For more information about database parameters supported by the SNC
interface, see Connection Reference.
122 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
The precision setting is for table creation only. When retrieving or updating the
data in a column, PowerBuilder uses only up to six decimal places precision for
fractional seconds, even if you enter a higher precision value for the column.
Filestream datatype The FILESTREAM datatype allows large binary data to be stored directly in
an NTFS file system. Transact-SQL statements can insert, update, query,
search, and back up FILESTREAM data.
The SQL Server Database Engine implements FILESTREAM as a
Varbinary(max) datatype. The PowerBuilder SNC interface maps the
Varbinary(max) datatype to a BLOB datatype, so to retrieve or update
filestream data, use the SelectBlob or UpdateBlob SQL statements,
respectively. To specify that a column should store data on the file system, you
must include the FILESTREAM attribute in the Varbinary(max) column
definition. For example:
CREATE TABLE FSTest (
GuidCol1 uniqueidentifier ROWGUIDCOL NOT NULL
UNIQUE DEFAULT NEWID(),
IntCol2 int,
varbinaryCol3 varbinary(max) FILESTREAM);
Using CLR datatypes The binary values of the .NET Common Language Runtime (CLR) datatypes
in PowerBuilder can be retrieved from a SQL Server database as blobs that you could use in
PowerBuilder applications to update other columns in the database. If their
return values are compatible with PowerBuilder datatypes, you can use CLR
datatype methods in PowerScript, dynamic SQL, embedded SQL or in
DataWindow objects, because the SQL script is executed on the SQL Server
side.
The CLR datatypes can also be mapped to Strings in PowerScript, but the
retrieved data is a hexadecimal string representation of binary data.
You can use the ToString method to work with all datatypes that are
implemented as CLR datatypes, such as the HierarchyID datatype, Spatial
datatypes, and User-defined types.
124 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
HierarchyID datatype HierarchyID is a variable length, system datatype that can store values
representing nodes in a hierarchical tree, such as an organizational structure. A
value of this datatype represents a position in the tree hierarchy.
ISQL Usage You can use HierarchyID columns with CREATE TABLE,
SELECT, UPDATE, INSERT, and DELETE statements in the ISQL painter.
For example:
CREATE TABLE Emp (
EmpId int NOT NULL,
EmpName varchar(20) NOT NULL,
EmpNode hierarchyid NULL);
To insert HierarchyID data, you can use the canonical string representation of
HierarchyID or any of the methods associated with the HierarchyID datatype
as shown below.
INSERT into Emp VALUES (1, 'Scott',
hierarchyid::GetRoot());
INSERT into Emp VALUES (2, 'Tom' , '/1/');
126 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
The geography and geometry datatypes support eleven different data objects,
or instance types, but only seven of these types are instantiable: Points,
LineStrings, Polygons, and the objects in an instantiable GeometryCollection
(MultiPoints, MultiLineStrings, and MultiPolygons). You can create and work
with these objects in a database, calling methods associated with them, such as
STAsText, STArea, STGeometryType, and so on.
For example:
CREATE TABLE SpatialTable (id int IDENTITY (1,1),
GeomCol geometry);
INSERT INTO SpatialTable (GeomCol) VALUES (
geometry::STGeomFromText(
'LINESTRING (100 100,20 180,180 180)',0));
select id, GeomCol.ToString() from SpatialTable;
select id, GeomCol.STAsText(),
GeomCol.STGeometryType(),
GeomCol.STArea() from SpatialTable;
User-defined types User-defined types (UDTs) are implemented in SQL Server as CLR types and
integrated with .NET. Microsoft SQL Server 2008 eliminates the 8 KB limit for
UDTs, enabling the size of UDT data to expand dramatically.
Although the PowerBuilder SNC interface does not directly support UDT
datatypes, you can use the ToString method to retrieve data for UDTs in the
same way as for other CLR datatypes such as HierarchyId or the spatial
datatypes. However, if a UDT datatype is mapped to a String datatype in
PowerScript, UDT binary values will be retrieved as hexadecimal strings. To
retrieve or update data in binary form (blob) from a UDT, you can use the
SelectBlob or UpdateBlob SQL statements, respectively.
You can use any of the associated methods of UDT or CLR datatypes that
return compatible data (such as String, Long, Decimal, and so on) for
PowerBuilder applications.
T-SQL enhancements
MERGE statement The MERGE Transact-SQL statement performs INSERT, UPDATE, or
DELETE operations on a target table or view based on the results of a join with
a source table. You can use MERGE statement in the ISQL painter and in
PowerScript using dynamic SQL. For example
String mySQL
mySQL = "MERGE INTO a USING b ON a.keycol = b.keycol " &
+ "WHEN MATCHED THEN "&
Grouping sets GROUPING SETS is an extension of the GROUP BY clause that lets you
define multiple groupings in the same query. GROUPING SETS produce a
single result set, making aggregate querying and reporting easier and faster. It
is equivalent to a UNION ALL operation for differently grouped rows.
The GROUPING SETS, ROLLUP, and CUBE operators are added to the
GROUP BY clause. A new function, GROUPING_ID, returns more
grouping-level information than the existing GROUPING function. (The
WITH ROLLUP, WITH CUBE, and ALL syntax is not ISO compliant and is
therefore deprecated.)
The following example uses the GROUPING SETS operator and the
GROUPING_ID function:
SELECT EmpId, Month, Yr, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS((EmpId, ROLLUP(Yr, Month)));
SELECT COL1, COL2,
SUM(COL3) AS TOTAL_VAL,
GROUPING(COL1) AS C1,
GROUPING(COL2) AS C2,
GROUPING_ID(COL1, COL2) AS GRP_ID_VALUE
FROM TEST_TBL GROUP BY ROLLUP (COL1, COL2);
You can use the GROUPING SETS operator in the ISQL painter, in
PowerScript (embedded SQL and dynamic SQL) and in DataWindow objects
(syntax mode).
128 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
Row constructors Transact-SQL now allows multiple value inserts within a single INSERT
statement. You can use the enhanced INSERT statement in the ISQL painter
and in PowerScript (embedded SQL and dynamic SQL). For example:
INSERT INTO Employees VALUES ('tom', 25, 5),
('jerry', 30, 6), ('bok', 25, 3);
When including multiple values in a single INSERT statement with host
variables, you must set the DisableBind DBParm to 1. If you use literal values
as in the above example, you can insert multiple rows in a single INSERT
statement regardless of the binding setting.
Compatibility level In SQL Server 2008, the ALTER DATABASE statement allows you to set the
database compatibility level (SQL Server version), replacing the
sp_dbcmptlevel procedure. You can use this syntax in the ISQL painter and in
PowerScript (dynamic SQL). For example:
ALTER DATABASE <database_name>
SET COMPATIBILITY_LEVEL = {80 | 90 | 100}
80 = SQL Server 2000
90 = SQL Server 2005
100 = SQL Server 2008
Compatibility level affects behaviors for the specified database only, not for the
entire database server. It provides only partial backward compatibility with
earlier versions of SQL Server. You can use the database compatibility level as
an interim migration aid to work around differences in the behaviors of
different versions of the database.
Table hints The FORCESEEK table hint overrides the default behavior of the query
optimizer. It provides advanced performance tuning options, instructing the
query optimizer to use an index seek operation as the only access path to the
data in the table or view that is referenced by the query. You can use the
FORCESEEK table hint in the ISQL painter, in PowerScript (embedded SQL
and dynamic SQL), and in DataWindow objects (syntax mode).
For example:
Select ProductID, OrderQty from SalesOrderDetail
with (FORCESEEK);
130 PowerBuilder
CHAPTER 10 Using Microsoft SQL Server
Triggers and In the Objects view for SNC profiles in the Database painter, triggers display
synonyms in the for tables in the Tables folder and Microsoft SQL Server 2005 synonyms
Database painter
display for tables and views.
132 PowerBuilder
CHAPTER 11 Using Oracle
C HA P T E R 11 Using Oracle
About this chapter This chapter describes how to use the native Oracle database interfaces in
PowerBuilder.
Contents
Topic Page
Supported versions for Oracle 133
Supported Oracle datatypes 134
Basic software components for Oracle 136
Preparing to use the Oracle database 138
Defining the Oracle database interface 142
Using Oracle stored procedures as a data source 143
Using Oracle user-defined types 148
Support for HA event notification 150
ORA driver support for Oracle 11g features 150
The ORA database interface allows you to connect to Oracle 11g/12c servers
using Oracle 11g/12c Database Client or Oracle 11g/12c Instant Client. It
includes partial support for the XMLType datatype that it maps to the
PowerBuilder String datatype. It also supports session and connection pooling,
load balancing, the Oracle Client Cache, setting of an application driver name,
and access through a proxy. Oracle 11g clients can also connect to Oracle 10g
servers.
The O10 database interface allows you to connect to Oracle 10g servers using
Oracle 10g Database Client or Oracle 10g Instant Client. It supports
BINARY_FLOAT and BINARY_DOUBLE datatypes and increased size limits for
CLOB and NCLOB datatypes. Oracle 10g clients can connect to Oracle 10g
servers.
The ORA driver adds support for the XMLType datatype that was introduced
with Oracle 9i. However, you cannot use this datatype with embedded SQL
statements or in a report.
Accessing Unicode PowerBuilder can connect, save, and retrieve data in both ANSI/DBCS and
data Unicode databases, but it does not convert data between Unicode and
ANSI/DBCS. When character data or command text is sent to the database,
PowerBuilder sends a Unicode string. The driver must guarantee that the data
is saved as Unicode data correctly. When PowerBuilder retrieves character
data, it assumes the data is Unicode.
A Unicode database is a database whose character set is set to a Unicode
format, such as UTF-8, UTF-16, UCS-2, or UCS-4. All data must be in
Unicode format, and any data saved to the database must be converted to
Unicode data implicitly or explicitly.
134 PowerBuilder
CHAPTER 11 Using Oracle
A database that uses ANSI (or DBCS) as its character set might use special
datatypes to store Unicode data. These datatypes are NCHAR and NVARCHAR2.
Columns with this datatype can store only Unicode data. Any data saved into
such a column must be converted to Unicode explicitly. This conversion must
be handled by the database server or client.
A constant string is regarded as a char type by Oracle and its character set is
NLS_CHARACTERSET. However, if the datatype in the database is NCHAR
and its character set is NLS_NCHAR_CHARACTERSET, Oracle performs a
conversion from NLS_CHARACTERSET to
NLS_NCHAR_CHARACTERSET. This can cause loss of data. For example,
if NLS_CHARACTERSET is WE8ISO8859P1 and
NLS_NCHAR_CHARACTERSET is UTF8, when the Unicode data is
mapped to WE8ISO8859P1, the Unicode data is corrupted.
If you want to access Unicode data using NCHAR and NVARCHAR2 columns
or stored procedure parameters, use PowerBuilder variables to store the
Unicode data in a script using embedded SQL to avoid using a constant string,
and force PowerBuilder to bind the variables.
By default, the Oracle database interfaces bind all string data to internal
variables as the Oracle CHAR datatype to avoid downgrading performance. To
ensure that NCHAR and NVARCHAR2 columns are handled as such on the
server, set the NCharBind database parameter to 1 to have the drivers bind
string data as the Oracle NCHAR datatype.
For example, suppose table1 has a column c1 with the datatype NVARCHAR2.
To insert Unicode data into the table, set DisableBind to 0, set NCharBind to 1,
and use this syntax:
string var1
insert into table1 (c1) values(:var1);
If an Oracle stored procedure has an NCHAR or NVARCHAR2 input parameter
and the input data is a Unicode string, set the BindSPInput database parameter
to 1 to force the Oracle database to bind the input data. The Oracle database
interfaces are able to describe the procedure to determine its parameters,
therefore you do not need to set the NCharBind database parameter.
For a report to access NCHAR and NVARCHAR2 columns and retrieve data
correctly, set both DisableBind and StaticBind to 0. Setting StaticBind to 0
ensures that PowerBuilder gets an accurate datatype before retrieving.
TimeStamp datatype The TimeStamp datatype in Oracle9i and later is an extension of the Date
datatype. It stores the year, month, and day of the Date value plus hours,
minutes, and seconds:
Timestamp[fractional_seconds_precision]
The fractional_seconds_precision value is optional and provides the number of
digits for indicating seconds. The range of valid values for use with
PowerBuilder is 0-6.
Datatype conversion
When you retrieve or update columns, in general PowerBuilder converts data
appropriately between the Oracle datatype and the PowerScript datatype. Keep
in mind, however, that similarly or identically named Oracle and PowerScript
datatypes do not necessarily have the same definitions.
For information about the definitions of PowerScript datatypes, see the
PowerScript Reference.
Number datatype When a DataWindow object is defined in PowerBuilder, the Oracle datatype
converted to decimal number(size,d) is mapped to a decimal datatype. In PowerBuilder, the precision
of a decimal is 18 digits. If a column’s datatype has a higher precision, for
example number(32,30), inserting a number with a precision greater than 18
digits produces an incorrect result when the number is retrieved in a
DataWindow. For example, 1.8E-17 displays as 0.000000000000000018,
whereas 1.5E-25 displays as 0.
You might be able to avoid this problem by using a different datatype, such as
float, for high precision number columns in the Oracle DBMS. The float
datatype is mapped to the number datatype within the DataWindow’s source.
136 PowerBuilder
CHAPTER 11 Using Oracle
138 PowerBuilder
CHAPTER 11 Using Oracle
Step 4: Determine Oracle client interface (OCI) pooling for PowerBuilder applications is created
whether to use when you connect to an Oracle server for the first time. The pooling is
connection or session
pooling identified by the server name and character set which are passed in the
DBPARM parameters SQLCA.ServerName and NLS_Charset, respectively. If
two Oracle connections are connected to the same Oracle server but use
different character sets, the connections must reside in different connection or
session pools. All pooling-related DBPARM parameters must be set before the
initial database connection from PowerBuilder.
Session pooling means that the application creates and maintains a group of
stateless sessions to the database. These sessions are passed to thin clients as
requested. If no session is available, a new one is created. When the client is
done with the session, the client releases it to the pool. With session pooling,
the number of sessions in the pool can increase dynamically.
Session pooling does not support external authentication using an OS account.
If a Login ID is not specified in a database connection using an existing session
pool, the Login ID of the session pooling creator is used for the connection.
140 PowerBuilder
CHAPTER 11 Using Oracle
Setting pooling parameters The database profile dialog box for an Oracle
11g connection includes a Pooling tab that lets you select the pooling
parameters listed in Table 11-4.
Table 11-4: Pooling parameters for the ORA driver
Pooling parameter Description
Pooling Type You can select Session Pooling, Connection Pooling, or
None (default). Sets the Pooling DBPARM.
Runtime Connection This check box selected by default. It is ignored when you
Load Balancing select Connection Pooling or None for the Pooling Type.
Sets the RTConnBalancing DBPARM.
Homogeneous Session This check box is not selected by default and is valid for
session pooling only. When selected, all sessions in the
pool are authenticated with the user name and password in
effect when the session pool was created. The user name
and password in later connection requests are ignored.
Proxy sessions cannot be created in homogeneous
sessioon mode. Sets the SessionHomogeneous DBPARM.
Minimum Number of Integer for the minimum number of database connection
Sessions sessions; value is 1 by default. Sets the CSMin DBPARM.
This value is ignored when the SessionHomogeneous
DBPARM is set to false.
Maximum Number of Integer for the maximum number of database connection
Sessions sessions; value is 100 by default. Sets the CSMax
DBPARM.
Increment Integer for database connection increments per session;
value is 1 by default. Sets the CSIncr DBPARM. This
value is ignored when the SessionHomogeneous
DBPARM is set to false.
Pool Creator User name used to create the connection or session pool
when the pool is not already created. Sets the PoolCreator
DBParm to a string for the user name prior to the database
connection. If you do not provide a value for the
PoolCreator DBParm, the Transaction object’s LogID and
LogPass properties are used to create the pooling.
Parameter Description
@ The at ( @ ) sign is required
TNS The identifier for the Oracle Transparent Network
Substrate (TNS) technology
142 PowerBuilder
CHAPTER 11 Using Oracle
Parameter Description
: The colon ( : ) is required
OracleServiceName The service name assigned to your server in the Oracle
configuration file for your platform
Net9 example To use Net9 client software to connect to the service named
ORA9, type the following connect descriptor in the Server box on the
Connection tab of the Database Profile Setup dialog box for Oracle9i and later:
ORA9.
For information about the syntax for using the DECLARE PROCEDURE
statement with the RPCFUNC keyword, see the PowerScript Reference.
Procedures with a single result set You can use stored procedures that
return a single result set in reports and embedded SQL, but not when using the
RPCFUNC keyword to declare the stored procedure as an external function or
subroutine.
Procedures with multiple result sets You can use procedures that return
multiple result sets only in embedded SQL. Multiple result sets are not
supported in DataWindows, reports, or with the RPCFUNC keyword.
144 PowerBuilder
CHAPTER 11 Using Oracle
4 Type the character you want (for example, a backquote) in the SQL
Terminator Character box.
5 Click Apply or OK.
The SQL Terminator Character setting is applied to the current connection
and all future connections (until you change it).
Creating the stored After setting up the Database painter, you can create an Oracle stored
procedure procedure that has a result set as an IN OUT (reference) parameter.
PowerBuilder retrieves the result set to populate a report.
There are many ways to create stored procedures with result sets. The
following procedure describes one possible method that you can use.
For information about when you can use stored procedures with single and
multiple result sets, see What you can do with Oracle stored procedures on
page 143.
3 Create an Oracle package that holds the result set type and stored
procedure. The result type must match your table definition.
Error checking
If necessary, check the Oracle system table public.user_errors for a list of errors.
146 PowerBuilder
CHAPTER 11 Using Oracle
Creating the report After you create the stored procedure, you can define the report that uses the
stored procedure as a data source.
You can use Oracle stored procedures that return a single result set in a report.
If your stored procedure returns multiple result sets, you must use embedded
SQL commands to access it.
The following procedure assumes that your Oracle stored procedure returns
only a single result set.
Example Here is a simple example that shows how you might create and use Oracle
user-defined types in PowerBuilder.
For more information about Oracle user-defined types, see your Oracle
documentation.
148 PowerBuilder
CHAPTER 11 Using Oracle
150 PowerBuilder
CHAPTER 11 Using Oracle
Application driver An OCI application can choose its own name and set it as a diagnostic aid. The
name AppDriverName DPBARM parameter allows you to set your own client driver
name for the PowerBuilder ORA interface. The maximum length of the name
is 8 characters. You can display the client driver name with the
V$SESSION_CONNECT_INFO or GV$SESSION_CONNECT_INFO
dynamic performance view queries.
Client access through The PowerBuilder ORA driver supports the proxy authentication feature that
a proxy (Oracle 10.2 was introduced in Oracle 10.2. With proxy authentication, the end user
feature)
typically authenticates to a middle tier (such as a firewall), that in turn logs into
the database on the user's behalf—as a proxy user. After logging into the
database, the proxy user can switch to the end user's identity and perform
operations using the authorization accorded to that user.
The ConnectAs DBParm parameter allows you to take advantage of this proxy
connection feature. For example, if the user’s Transaction object LogID is
“Scott” and you set the ConnectAs DBParm parameter to “John”, the OCI
client logs in to database as the proxy user (“Scott”), then switches to the end
user identity (“John”).
If you are using connection or session pooling, the proxy user name is the
connection or session pooling creator (which you can provide in the
PoolCreator and PoolPwd DBParm parameters), and the Transaction object’s
LogID is ignored. No proxy session can be created if pooling is set to
HomogeneousSession mode.
Load balancing The Oracle Real Application Clusters (RAC) database option allows a single
database to be hosted in multiple instances on multiple nodes of the database
server. This adds high availability and failover capacity to the database.
Availability is improved since, if one node fails, another node can assume its
workload. All instances have access to the whole database. The shared disk
method of clustering databases used by the RAC option increases scalability
because nodes can be added or freed as required.
In RAC environments, session pools can use service metrics received from the
RAC load balancing advisory to balance application session requests. The
work requests coming into the session pool can then be distributed across the
instances of RAC based on current service performance.
Connect time load balancing Balancing of work requests occur at two
different times: connect time and runtime. Connect time load balancing occurs
when a session is first created by the application. This ensures that sessions that
are part of the pool are well distributed across RAC instances, and that sessions
on each of the instances get a chance to execute work.
For session pools that support services at one instance only, the first available
session in the pool is adequate. When the pool supports services that span
multiple instances, there is a need to distribute the work requests across
instances so that the instances that are providing better service or have greater
capacity get more requests.
Runtime connection load balancing Runtime connection load balancing
basically routs work requests to the sessions in a session pool that best serve
the work. Runtime connection load balancing is enabled by default when an
Oracle 11.1 or higher client is connected to a 10.2 or higher Oracle server using
OCI session pooling.
The DBPARM parameter, RTConnBalancing, supports the runtime connection
load balancing feature. It is available only when the Pooling parameter is set to
Session Pooling, and it can be set before connection only. By default, when you
select Session Pooling for the pooling type, the RTConnBalancing value is
true.
152 PowerBuilder
CHAPTER 12 Using DirectConnect
C HA P T E R 1 2 Using DirectConnect
About this chapter This chapter describes how to use the DirectConnect™ interface in
PowerBuilder.
Contents
Topic Page
Using the DirectConnect interface 153
Supported versions for the DirectConnect interface 155
Supported DirectConnect interface datatypes 156
Basic software components for the DirectConnect interface 157
Preparing to use the database with DirectConnect 158
Defining the DirectConnect interface 161
Creating the extended attribute system tables in DB2 databases 162
A database that uses ANSI (or DBCS) as its character set might use special
datatypes to store Unicode data. Columns with these datatypes can store only
Unicode data. Any data saved into such a column must be converted to
Unicode explicitly. This conversion must be handled by the database server or
client.
154 PowerBuilder
CHAPTER 12 Using DirectConnect
156 PowerBuilder
CHAPTER 12 Using DirectConnect
158 PowerBuilder
CHAPTER 12 Using DirectConnect
For information about Open Client, see your Open Client documentation.
5 Make sure the Open Client software is properly configured so you can
connect to the middleware data access product at your site.
Installing the Open Client software places the SQL.INI configuration file
in the SQL Server directory on your computer. SQL.INI provides
information that SQL Server uses to find and connect to the middleware
product at your site. You can enter and modify information in SQL.INI
with the configuration utility or editor that comes with the Open Client
software.
For information about editing the SQL.INI file, see Editing the SQL.INI
file on page 161. For more information about setting up SQL.INI or any
other required configuration file, see your SQL Server documentation.
6 If required by your operating system, make sure the directory containing
the Open Client software is in your system path.
7 Make sure only one copy of each of the following files is installed on your
client computer:
• DirectConnect interface DLL
• Network communication DLL (such as NLWNSCK.DLL for Windows
Sockets-compliant TCP/IP)
• Open Client DLLs (such as LIBCT.DLL and LIBCS.DLL)
Step 2: Install the In the PowerBuilder Setup program, select the Typical install, or select the
interface Custom install and select the Direct Connect Interface (DIR).
Step 3: Verify the Make sure you can connect to your middleware product and your database and
connection log in to the database you want to access from outside PowerBuilder.
Some possible ways to verify the connection are by running the following
tools:
• Accessing the database server Tools such as the Open Client/Open
Server Configuration utility (or any Ping utility) check whether you can
reach the database server from your computer.
• Accessing the database Tools such as ISQL or SQL Advantage
(interactive SQL utilities) check whether you can log in to the database
and perform database operations. It is a good idea to specify the same
connection parameters you plan to use in your PowerBuilder database
profile to access the database.
160 PowerBuilder
CHAPTER 12 Using DirectConnect
Step 4: Create the PowerBuilder uses a collection of five system tables to store extended attribute
extended attribute information. When using the DirectConnect interface, you must create the
system tables
extended attribute system tables outside PowerBuilder to control the access
rights and location of these tables.
Run the DB2SYSPB.SQL script outside PowerBuilder using the SQL tool of
your choice.
For instructions, see Creating the extended attribute system tables in DB2
databases on page 162.
Editing the SQL.INI Make sure the SQL.INI file provides an entry about either the access service
file being used and the DirectConnect server on which it resides or the Open
ServerConnect program being used and the mainframe on which it resides.
For the server object name, you need to provide the exact access service name
as it is defined in the access service library configuration file on the
DirectConnect server. You must also specify the network communication DLL
being used, the TCP/IP address or alias used for the DirectConnect server on
which the access service resides, and the port on which the DirectConnect
server listens for requests:
[access_service_name]
query=network_dll,server_alias,server_port_no
PowerBuilder users must also specify the access service name in the
SQLCA.ServerName property of the Transaction object.
To ensure that the extended attribute system tables are created with the
proper access rights:
• Make sure the first person to connect to the database with PowerBuilder
has sufficient authority to create tables and grant permissions to PUBLIC.
This means that the first person to connect to the database should log in as
the database owner, database administrator, system user, system
administrator, or system owner, as specified by your DBMS.
162 PowerBuilder
CHAPTER 12 Using DirectConnect
What you do To create the extended attribute system tables, you run the DB2SYSPB.SQL
script outside PowerBuilder. This script contains SQL commands that create
and initialize the system tables with the table owner and tablespace you specify.
Where to find The DB2SYSPB.SQL script is in the Server directory in the PowerBuilder setup
DB2SYSPB.SQL program. This directory contains server-side installation components and is not
installed with PowerBuilder on your computer.
You can access the DB2SYSPB.SQL script by copying it to your computer.
Use the following procedure from the database server to create the extended
attribute system tables in a DB2 database outside PowerBuilder. This
procedure assumes you are accessing the DB2SYSPB.SQL script from
d:\server.
PBCatalogOwner
If you changed PBOwner to another name in the DB2SYSPB.SQL script,
you must specify the new owner name as the value for the
PBCatalogOwner DBParm parameter in your database profile. For
instructions, see PBCatalogOwner in the online Help.
164 PowerBuilder
PA RT 4 Working with Database
Connections
165
CHAPTER 13 Managing Database Connections
About this chapter After you install the necessary database software and define the database
interface, you can connect to the database from PowerBuilder. Once you
connect to the database, you can work with the tables and views stored in that
database.
This chapter describes how to connect to a database in PowerBuilder, maintain
database profiles, and share database profiles.
Contents
Topic Page
About database connections 167
Connecting to a database 169
Maintaining database profiles 172
Sharing database profiles 173
Importing and exporting database profiles 177
About the PowerBuilder extended attribute system tables 178
Terminology In this chapter, the term database refers to both of the following unless
otherwise specified:
• A database or DBMS that you access with a standard database interface
and appropriate driver
• A database or DBMS that you access with the appropriate native database
interface
168 PowerBuilder
CHAPTER 13 Managing Database Connections
Because database profiles are created when you define your data and are stored
in the registry, they have the following benefits:
• They are always available to you.
• Connection parameters supplied in a database profile are saved until you
edit or delete the database profile.
Connecting to a database
To establish or change a database connection in PowerBuilder, use a database
profile. You can select the database profile for the database you want to access
in the Database Profiles dialog box. For how to create a database profile, see
Creating a database profile on page 9.
The Database Profiles dialog box displays, listing your installed database
interfaces.
2 Click the plus sign (+) to the left of the interface you are using or
double-click the name.
The list expands to display the database profiles defined for your interface.
3 Select the name of the database profile you want to access and click
Connect or display the pop-up menu for a database profile and select
Connect.
PowerBuilder connects to the specified database and returns you to the
painter workspace.
Database painter You can select a database profile from the Database painter Objects view.
Objects view
2 Click the plus sign (+) to the left of the interface you are using or
double-click the name.
The list expands to display the database profiles defined for your interface.
3 Select the name of the database profile you want to access and click the
Connect button, or display the pop-up menu for a database profile and
select Connect.
170 PowerBuilder
CHAPTER 13 Managing Database Connections
2 Leave the Password box blank. Instead, specify the password in the dialog
box that displays to prompt you for additional information when you
connect to the database.
What happens When you specify the password in response to a prompt instead of in the
Database Profile Setup dialog box, the password does not display in the
registry entry for this profile.
For example, if you do not supply a password in the Database Profile Setup -
Adaptive Server Enterprise dialog box when creating a database profile, the
Client Library Login dialog box displays to prompt you for the missing
information.
172 PowerBuilder
CHAPTER 13 Managing Database Connections
This section describes what you need to know to set up, use, and maintain
shared database profiles in PowerBuilder.
3 Click OK.
PowerBuilder applies the Shared Database Profiles setting to the current
connection and all future connections and saves the setting in the registry.
174 PowerBuilder
CHAPTER 13 Managing Database Connections
2 Select the name of the shared profile you want to access and click Connect.
PowerBuilder connects to the selected database and returns you to the
painter workspace.
176 PowerBuilder
CHAPTER 13 Managing Database Connections
To import a profile:
1 Highlight a database interface and select Import Profile(s) from the pop-up
menu. (In the Database painter, select Import Profile(s) from the File or
pop-up menu.)
2 From the Select Profile File dialog box, select the file whose profiles you
want to import and click Save.
3 Select the profile(s) you want to import from the Import Profile(s) dialog
box and click OK.
The profiles are copied into your registry. If a profile with the same name
already exists, you are asked if you want to overwrite it.
To export a profile:
1 Highlight a database interface and select Export Profile(s) from the pop-up
menu. (In the Database painter, select Export Profile(s) from the File or
pop-up menu.)
2 Select the profile(s) you want to export from the Export Profile(s) dialog
box and click OK.
The Export Profile(s) dialog box lists all profiles defined in your registry
regardless of the database interface for which they were defined. By
default, the profiles defined for the selected database interface are marked
for export.
3 From the Select Profile File dialog box, select a directory and a file in
which to save the exported profile(s) and click Save.
The exported profiles can be saved to a new or existing file. If saved to an
existing file, the profile(s) are added to the existing profiles. If a profile
with the same name already exists, you are asked if you want to overwrite
it.
178 PowerBuilder
CHAPTER 13 Managing Database Connections
180 PowerBuilder
CHAPTER 13 Managing Database Connections
For more about the PowerBuilder system tables, see the Appendix in the Users
Guide.
The preceding table gives the base name of each system table without the
DBMS-specific prefix.
• Setting Read Only Set the Read Only database preference in the
Database Preferences dialog box in the Database painter.
• Granting permissions on the system tables Grant explicit
permissions on the system tables to users or groups at your site.
182 PowerBuilder
CHAPTER 13 Managing Database Connections
2 On the General page, set values for Use Extended Attributes or Read Only
as follows:
Preference What you do Effect
Use Extended Attributes Clear the check box Does not create the PowerBuilder system tables if they do not
exist. Instead, the painter uses the appropriate default values
for extended attributes (such as headers, labels, and text
color).
If the PowerBuilder system tables already exist,
PowerBuilder does not use them when you create a new
report.
Read Only Select the check box If the PowerBuilder system tables already exist,
PowerBuilder uses them when you create a new report, but
does not update them.
You cannot modify (update) information in the system tables
or any other database tables in the Report painter when the
Read Only check box is selected.
3 Click OK.
PowerBuilder applies the preference settings to the current connection and
all future connections and saves them in the registry.
184 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
About this chapter To fine-tune your database connection and take advantage of DBMS-specific
features that your interface supports, you can set additional connection
parameters at any time. These additional connection parameters include:
• Database parameters
• Database preferences
These connection parameters are described in the Database Connectivity
section in the online Help.
This chapter describes how to set database parameters and database
preferences in PowerBuilder.
Contents
Topic Page
Basic steps for setting connection parameters 185
About the Database Profile Setup dialog box 186
Setting database parameters 187
Setting database preferences 190
2 Determine the database parameters you can set for your database interface.
For a table listing each supported database interface and the database
parameters you can use with that interface, see “Database parameters and
supported database interfaces” in the online Help.
3 Read the description of the database parameter you want to set in the
online Help.
4 Set the database parameter for your database connection.
186 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
To copy DBParm syntax from the Preview tab into your code:
1 On one or more tab pages in the Database Profile Setup dialog box for your
connection, supply values for any parameters you want to set.
For instructions, see Setting database parameters in the development
environment on page 187.
For information about the parameters for your interface and the values to
supply, click Help.
2 Click Apply to save your changes to the current tab without closing the
Database Profile Setup dialog box.
3 Click the Preview tab.
The correct DBParm syntax for each selected option displays in the
Database Connection Syntax box.
188 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
4 Select one or more lines of text in the Database Connection Syntax box
and click Copy.
PowerBuilder copies the selected text to the clipboard.
5 Click OK to close the Database Profile Setup dialog box.
6 Paste the selected text from the Preview tab into your code, modifying the
default Transaction object name (SQLCA) if necessary.
190 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
The following sections give the steps for setting database preferences in the
development environment and (for AutoCommit and Lock) in a PowerBuilder
application script.
For more information For information about using a specific database preference, see its description
in the online Help.
ADO.NET
For ADO.NET, Isolation is a database parameter.
• Set all other database preferences in the Database Preferences dialog box
in the Database painter
192 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
5 (Optional) In PowerBuilder, click the Preview tab if you want to see the
PowerScript connection syntax generated for Lock and AutoCommit.
PowerBuilder generates correct PowerScript connection syntax for each
option you set in the Database Profile Setup dialog box. You can copy this
syntax directly into a PowerBuilder application script.
For instructions, see Copying DBParm syntax from the Preview tab on
page 188.
6 Click OK to close the Database Profile Setup dialog box.
PowerBuilder saves your settings in the database profile entry in the
registry.
194 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
To copy AutoCommit and Lock syntax from the Preview tab into your
script:
1 On the Connection tab in the Database Profile Setup dialog box for your
connection, supply values for AutoCommit and Lock (Isolation Level) as
required.
For instructions, see Setting AutoCommit and Lock in a PowerBuilder
application script on page 195.
For example, in addition to values for basic connection parameters
(Server, Login ID, Password, and Database), the Connection tab for the
following Adaptive Server profile named Sales shows nondefault settings
for Isolation Level and AutoCommit Mode.
For information about the DBParm parameters for your interface and the
values to supply, click Help.
2 Click Apply to save your changes to the current tab without closing the
Database Profile Setup dialog box.
3 Click the Preview tab.
The correct PowerScript syntax for each selected option displays in the
Database Connection Syntax box. For example:
196 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
4 Select one or more lines of text in the Database Connection Syntax box
and click Copy.
PowerBuilder copies the selected text to the clipboard.
5 Click OK to close the Database Profile Setup dialog box.
6 Paste the selected text from the Preview tab into your script, modifying the
default Transaction object name (SQLCA) if necessary.
198 PowerBuilder
CHAPTER 14 Setting Additional Connection Parameters
200 PowerBuilder
PA RT 5 Working with Transaction
Servers
201
CHAPTER 15 Troubleshooting Your Connection
C HA P T E R 1 5 Troubleshooting Your
Connection
About this chapter This chapter describes how to troubleshoot your database connection in
PowerBuilder by using the following tools:
• Database Trace
• SQL Statement Trace
• ODBC Driver Manager Trace
• JDBC Driver Manager Trace
Contents
Topic Page
Overview of troubleshooting tools 203
Using the Database Trace tool 204
Using the SQL statement trace utility 217
Using the ODBC Driver Manager Trace tool 219
Using the JDBC Driver Manager Trace tool 227
204 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
Registry settings for The selections made in the Database Trace dialog box are saved to the registry
DBTrace of the machine from which the database connections are made. Windows
registry settings for the database trace utility configuration are stored under the
HKEY_CURRENT_USER\Software\Sybase\PowerBuilder\17.0\DBTrace key.
Registry strings under this key are: ShowBindings, FetchBuffers,
ShowDBINames, Timing, SumTiming, LogFileName, and ShowDialog.
Except for the LogFileName string to which you can assign a full file name for
the trace output file, all strings can be set to either 0 or 1.
The ShowDialog registry string can be set to prevent display of the Database
Trace dialog box when a database connection is made with tracing enabled.
This is the only one of the trace registry strings that you cannot change from
the Database Trace dialog box. You must set ShowDialog to 0 in the registry to
keep the configuration dialog box from displaying.
INI file settings for If you do not have access to the registry, you can use PB.INI to store trace file
DBTrace settings. Add a [DbTrace] section to the INI file with at least one of the
following values set, then restart PowerBuilder:
[DbTrace]
ShowDBINames=0
FetchBuffers=1
ShowBindings=1
SumTiming=1
Timing=1
ShowDialog=1
LogFileName=dbtrace.log
The keywords are the same as in the registry and have the same meaning. When
you connect to the database again, the initial settings are taken from the INI
file, and when you modify them, the changes are written to the INI file.
If the file name for LogFileName does not include an absolute path, the log file
is written to the following path, where <username> is your login ID:
Users\<username>\AppData\Local\Appeon\PowerBuilder 17.0. If there are
no DbTrace settings in the INI file, the registry settings are used.
Error messages If the database trace utility cannot open the trace output file with write access,
an error message lets you know that the specified trace file could not be created
or opened. If the trace utility driver cannot be loaded successfully, a message
box informs you that the selected Trace DBMS is not supported in your current
installation.
206 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
Parameter Description
COMMAND The internal command that PowerBuilder executes
to perform the database operation.
time The number of microseconds it takes PowerBuilder
to perform the database operation. The precision
used depends on your operating system’s timing
mechanism.
additional_information (Optional) Additional information about the
command. The information provided depends on
the database operation.
Example The following portion of the log file shows the commands PowerBuilder
executes to fetch two rows from a SQL Anywhere database table:
FETCH NEXT: (0.479 MS)
COLUMN=400 COLUMN=Marketing COLUMN=Evans
FETCH NEXT: (0.001 MS)
COLUMN=500 COLUMN=Shipping COLUMN=Martinez
If you opt to include DBI Names and Sum Time information in the trace log
file, the log for the same two rows might look like this:
FETCH NEXT:(DBI_FETCHNEXT) (1.459 MS / 3858.556 MS)
COLUMN=400 COLUMN=Marketing COLUMN=Evans
FETCH NEXT:(DBI_FETCHNEXT) (0.001 MS / 3858.557 MS)
COLUMN=500 COLUMN=Shipping COLUMN=Martinez
For a more complete example of Database Trace output, see Sample Database
Trace output on page 215.
208 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
To copy DBMS trace syntax from the Preview tab into your script:
1 On the Connection tab (or System tab in the case of OLE DB) in the
Database Profile Setup dialog box for your connection, select the Generate
Trace check box to turn on Database Trace.
For instructions, see Starting Database Trace in the development
environment on page 208.
2 Click Apply to save your changes to the Connection tab without closing
the Database Profile Setup dialog box.
3 Click the Preview tab.
The correct PowerScript connection syntax for the Generate Trace and
other selected options displays in the Database Connection Syntax box.
4 Select the SQLCA.DBMS line and any other syntax you want to copy to
your script and click Copy.
PowerBuilder copies the selected text to the clipboard.
5 Click OK to close the Database Profile Setup dialog box.
6 Paste the selected text from the Preview tab into your script, modifying the
default Transaction object name (SQLCA) if necessary.
Coding PowerScript to Another way to start the Database Trace tool in a PowerBuilder script is to
set a value for the specify it as part of the DBMS property of the Transaction object. The
DBMS property
Transaction object is a special nonvisual object that PowerBuilder uses to
communicate with the database. The default Transaction object is named
SQLCA, which stands for SQL Communications Area.
SQLCA has 15 properties, 10 of which are used to connect to your database.
One of the 10 connection properties is DBMS. The DBMS property contains
the name of the database to which you want to connect.
210 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
To start the Database Trace tool by reading the DBMS value from an
external text file:
• Use the following PowerScript syntax to specify the ProfileString function
with the DBMS property:
SQLCA.DBMS = ProfileString(file, section, variable, default_value)
For example, the following statement in a PowerBuilder script reads the
DBMS value from the [Database] section of the APP.INI file:
SQLCA.DBMS=ProfileString("APP.INI","Database",
"DBMS","")
For how to get a value from a registry file instead, see Getting values from the
registry on page 198.
For example, if you wanted data to be logged to the trace output for a single
retrieve command, you could disable tracing from the start of the connection
and then surround the retrieve call with DBParm property assignments as
follows:
SQLCA.DBMS = "TRACE ODBC"
SQLCA.DBParm="PBTrace=0"
Connect using SQLCA;
...
SQLCA.DBParm="PBTrace=1"
dw_1.Retrieve ( )
SQLCA.DBParm="PBTrace=0"
When you first connect to a database after setting the DBMS parameter to
“Trace DBMSName”, a configuration dialog box displays. The configuration
parameters that you set in this dialog box are saved to the registry.
Configuration parameters are retrieved from the registry when you begin
tracing by assigning the DBParm parameter to "PBTrace=1".
You can start and stop the SQL statement trace utility in the same way if you
set the DBMS value to “TRS DBMSName” instead of “Trace DBMSName”.
For information about the SQL statement trace utility, see Using the SQL
statement trace utility on page 217.
212 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
214 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
216 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
PBTRS170.DLL obtains the date and time from the server only once during the
database connection processing. Each time a new timestamp needs to be
generated, it determines the number of milliseconds that have transpired since
the connection was established and computes the new server-side date and time
by adding the elapsed interval to the initial connection timestamp obtained
from the server.
Log file headers Output to the log file is always appended. For ease of reading, the
PBTRS170.DLL produces a banner inside the log file each time a new database
connection is established. The banner lists the date and time of the database
connection using the system clock on the client workstation. The DBParms for
the database connection are listed immediately under the banner. If a server
timestamp is used for subsequent entries in the log file, the statement “Using
timestamp from DBMS server” is entered immediately under the DBParm
listings.
When you are running an application with a database trace utility, one of the
DBParm values should include the DisableBind parameter. You should set
DisableBind to 1. Otherwise the syntax that is logged in the trace output file
will contain parameter markers instead of human-readable values.
The following output shows a banner from a trace file that uses a client-side
timestamp in the banner itself, and server-side timestamps elsewhere:
/*---------------------------------------------------*/
/* 1/10/2007 16:08 */
/*---------------------------------------------------*/
(60ec068): CONNECT TO TRS ODBC: DBPARM=ConnectString='DSN= PB
Demo DB V2017;UID=dba;PWD=sql' SERVER=DemoDatabase170
(60ec068): Using timestamp from DBMS server. (1/10/2007
16:08:28.079)
(60ec068): PREPARE: (1/10/2007 16:08:44.513) SELECT
DISTINCT "pbcattbl"."pbt_tnam" , "pbcattbl"."pbt_cmnt"
FROM "pbcattbl" ORDER BY "pbcattbl"."pbt_tnam" ASC
218 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
Performance considerations
Turning on ODBC Driver Manager Trace can slow your performance while
working in PowerBuilder. Therefore, use ODBC Driver Manager Trace for
debugging purposes only and keep it turned off when you are not debugging.
SQL.LOG file PowerBuilder writes ODBC Driver Manager Trace output to a default log file
named SQL.LOG or to a log file that you specify. The default location of
SQL.LOG is in your root directory.
4 Click OK or Apply
or
Right-click on the connected database and select Re-connect from the
drop-down menu in the Database Profiles dialog box.
The Database Profiles dialog box displays with the name of the edited
profile highlighted.
PowerBuilder saves your settings in the database profile entry in the
registry in the
HKEY_CURRENT_USER\Software\Sybase\17.0\DatabaseProfiles key.
220 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
For example, here is the relevant portion of a database profile entry for an
ODBC data source named Employee. The settings that start ODBC Driver
Manager Trace (corresponding to the ConnectOption DBParm parameter)
are emphasized.
DBMS "ODBC"
...
DbParm "ConnectString='DSN=Emloyee;UID=dba;
PWD=00c61737',ConnectOption='SQL_OPT_TRACE,SQL_OPT_
TRACE_ON;SQL_OPT_TRACEFILE,C:\Temp\odbctrce.log'”
5 Click Connect in the Database Profiles dialog box to connect to the
database
or
Right-click on the connected database and select Re-connect from the
drop-down menu in the Database Profiles dialog box.
PowerBuilder connects to the database, starts tracing the ODBC
connection, and writes output to the log file you specified.
About the ConnectOption includes several parameters, two of which control the
ConnectOption operation of ODBC Driver Manager Trace for any ODBC-compatible driver
DBParm parameter
you are using in PowerBuilder.
Table 15-2: ConnectOption parameters for ODBC Driver Manager Trace
Parameter Description
SQL_OPT_TRACE Purpose Starts or stops ODBC Driver Manager
Trace in PowerBuilder.
Values The values you can specify are:
• SQL_OPT_TRACE_OFF
(Default) Stops ODBC Driver Manager Trace
• SQL_OPT_TRACE_ON
Starts ODBC Driver Manager Trace
SQL_OPT_TRACEFILE Purpose Specifies the name of the trace file
where you want to send the output of ODBC Driver
Manager Trace. PowerBuilder appends the output
to the trace file you specify until you stop the trace.
To display the trace file, you can use the File Editor
(in PowerBuilder) or any text editor (outside
PowerBuilder).
Values You can specify any filename for the trace
file, following the naming conventions of your
operating system. By default, if tracing is on and
you have not specified a trace file, PowerBuilder
sends ODBC Driver Manager Trace output to a file
named SQL.LOG.
For information about the location of SQL.LOG on
different platforms, see About ODBC Driver
Manager Trace on page 219.
Copying The easiest way to start ODBC Driver Manager Trace in a PowerBuilder
ConnectOption syntax application script is to copy the PowerScript ConnectString DBParm syntax
from the Preview tab
from the Preview tab in the Database Profile Setup - ODBC dialog box into
your script, modifying the default Transaction object name (SQLCA) if
necessary.
As you complete the Database Profile Setup dialog box in the development
environment, PowerBuilder generates the correct connection syntax on the
Preview tab. Therefore, copying the syntax directly from the Preview tab into
your script ensures that it is accurate.
222 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
To copy ConnectOption syntax from the Preview tab into your script:
1 On the Options tab in the Database Profile Setup - ODBC dialog box for
your connection, select the Trace ODBC API Calls check box and
(optionally) specify a log file in the Trace File box to start ODBC Driver
Manager Trace.
2 Click Apply to save your changes to the Options tab without closing the
dialog box.
3 Click the Preview tab.
The correct PowerScript syntax for ODBC Driver Manager Trace and
other selected options displays in the Database Connection Syntax box.
The following example shows the PowerScript syntax that starts ODBC
Driver Manager Trace and sends output to the file
C:\TEMP\ODBCTRCE.LOG.
// Profile Employee
SQLCA.DBMS = "ODBC"
SQLCA.AutoCommit = False
SQLCA.DBParm = "Connectstring='DSN=Employee',
ConnectOption='SQL_OPT_TRACE,SQL_OPT_TRACE_ON;
SQL_OPT_TRACEFILE,c:\temp\odbctrce.log’"
4 Select the SQLCA.DBParm line and any other syntax you want to copy to
your script and click Copy.
PowerBuilder copies the selected text to the clipboard.
5 Paste the selected text from the Preview tab into your script, modifying the
default Transaction object name (SQLCA) if necessary.
Coding PowerScript to Another way to start ODBC Driver Manager Trace in a PowerBuilder
set a value for the application script is to include the ConnectOption parameters that control
DBParm property
tracing as values for the DBParm property of the Transaction object.
SQLCA.DBParm="ConnectString=’DSN=Test;UID=PB;
PWD=xyz’,ConnectOption=’SQL_OPT_TRACE,
SQL_OPT_TRACE_ON;SQL_OPT_TRACEFILE,C:\TRC.LOG’"
Reading the DBParm As an alternative to setting the DBParm property in your PowerBuilder
value from an external application script, you can use the PowerScript ProfileString function to read
text file
DBParm values from a specified section of an external text file, such as an
application-specific initialization file.
This assumes that the DBParm value read from your initialization file includes
the ConnectOption parameter to start ODBC Driver Manager Trace, as shown
in the preceding example.
224 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
If you supplied the pathname of a log file in the Trace File box, you can
leave it specified in case you want to restart tracing later.
3 Click OK in the Database Profile Setup - ODBC dialog box.
The Database Profiles dialog box displays, with the name of the edited
profile highlighted.
4 Click Connect in the Database Profiles dialog box or right-click on the
connected database and select Re-connect from the drop-down menu in
the Database Profiles dialog box.
PowerBuilder connects to the database and stops tracing the connection.
Here is how the same statement should look after you edit it to stop ODBC
Driver Manager Trace. (You can leave the name of the trace file specified in
case you want to restart tracing later.)
SQLCA.DBParm="ConnectString=’DSN=Test;UID=PB;
PWD=xyz’,ConnectOption=’SQL_OPT_TRACE,
SQL_OPT_TRACE_OFF;SQL_OPT_TRACEFILE,C:\TRC.LOG’"
Reading DBParm As an alternative to editing the DBParm property in your PowerBuilder
values application script, you can use the PowerScript ProfileString function to read
DBParm values from a specified section of an external text file, such as an
application-specific initialization file.
This assumes that the DBParm value read from your initialization file sets the
value of SQL_OPT_TRACE to SQL_OPT_TRACE_OFF, as shown in the
preceding example.
Location of SQL.LOG
For information about where to find the default SQL.LOG file, see About
ODBC Driver Manager Trace on page 219.
226 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
What both tools do The information from JDBC Driver Manager Trace, like Database Trace, can
help you:
• Understand what PowerBuilder is doing internally while connected to a
database through the JDBC interface
• Identify and resolve problems with your JDBC connection
• Provide useful information to Technical Support if you call them for help
with your database connection
When to use this tool Use JDBC Driver Manager Trace instead of the Database Trace tool if you
want more detailed information about the JDBC driver.
Performance considerations
Turning on JDBC Driver Manager Trace can slow your performance while
working in PowerBuilder. Therefore, use JDBC Driver Manager Trace for
debugging purposes only and keep it turned off when you are not debugging.
JDBC.LOG file PowerBuilder writes JDBC Driver Manager Trace output to a default log file
named JDBC.LOG or to a log file that you specify. The default location of
JDBC.LOG is a temp directory.
228 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
3 (Optional) To specify a log file where you want PowerBuilder to write the
output of JDBC Driver Manager Trace, type the path name in the Trace
File box, or click Browse to display the path name of an existing log file
in the Trace File box.
By default, if the Trace JDBC Calls check box is selected and no
alternative trace file is specified, PowerBuilder sends JDBC Driver
Manager Trace output to the default JDBC.LOG file.
4 Click OK or Apply.
The Database Profiles dialog box displays with the name of the edited
profile highlighted. PowerBuilder saves your settings in the database
profile entry in the registry.
For example, here are the DBMS and DBParm string values of a database
profile entry for a database named Employee. The settings that start JDBC
Driver Manager Trace (corresponding to the TraceFile DBParm
parameter) are emphasized.
DBMS "TRACE JDBC"
DbParm "Driver='com.sybase.jdbc3.jdbc.SybDriver',
URL='jdbc:sybase:Tds:199.93.178.151:
5007/tsdata',TraceFile='c:\temp\jdbc.log'"
5 Click Connect in the Database Profiles dialog box to connect to the
database
or
Right-click on the connected database and select Re-connect from the
drop-down menu in the Database Profiles dialog box.
PowerBuilder connects to the database, starts tracing the JDBC
connection, and writes output to the log file you specified.
To copy TraceFile syntax from the Preview tab into your script:
1 On the Options tab in the Database Profile Setup - JDBC dialog box for
your connection, select the Trace JDBC Calls check box and (optionally)
specify a log file in the Trace File box to start JDBC Driver Manager
Trace.
For instructions, see Stopping JDBC Driver Manager Trace in the
development environment on page 232.
2 Click Apply to save your changes to the Options tab without closing the
dialog box.
3 Click the Preview tab.
The correct PowerScript syntax for JDBC Driver Manager Trace and other
selected options displays in the Database Connection Syntax box.
230 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
The following example shows the PowerScript syntax that starts JDBC
Driver Manager Trace and sends output to the file C:\TEMP\JDBC.LOG.
// Profile Employee
SQLCA.DBMS = "TRACE JDBC"
SQLCA.DBParm =
"Driver='com.sybase.jdbc3.jdbc.SybDriver',
URL='jdbc:sybase:Tds:199.93.178.151:5007/tsdata',
TraceFile='c:\temp\jdbc.log'"
4 Select the DBParm line and any other syntax you want to copy to your
script and click Copy.
PowerBuilder copies the selected text to the clipboard.
5 Paste the selected text from the Preview tab into your script, modifying the
default Transaction object name (SQLCA) if necessary.
Coding PowerScript to Another way to start JDBC Driver Manager Trace in a PowerBuilder
set a value for the application script is to include the TraceFile parameter as a value for the
DBParm property
DBParm property of the Transaction object.
232 PowerBuilder
CHAPTER 15 Troubleshooting Your Connection
Location of JDBC.LOG
For information about where to find the default JDBC.LOG file, see About
JDBC Driver Manager Trace on page 227.
234 PowerBuilder
PA RT 6 Using Embedded SQL
235
CHAPTER 16 Using Embedded SQL with ODBC
About this chapter When you create scripts for a PowerBuilder application, you can use embedded
SQL statements in the script to perform operations on the database. The
features supported when you use embedded SQL depend on the DBMS to
which your application connects.
Overview When you use the ODBC interface to connect to a backend database, you can
use embedded SQL in your scripts.
You can embed the following types of SQL statements in scripts and user-
defined functions if the ODBC driver you are using and the backend DBMS
you are accessing supports this functionality. (Not all backend databases
support cursor statements and database stored procedures.)
• Transaction management statements
• Non-cursor statements
• Cursor statements
• Database stored procedures
ODBC API The ODBC interface uses the ODBC application programming interface (API)
to interact with the backend database.
When you use embedded SQL, PowerBuilder makes the required calls to the
backend database. Therefore, you do not need to know anything about the
ODBC API to use embedded SQL with PowerBuilder.
See also Chapter 2, Using the ODBC Interface
ODBC SQL Support
ODBC Transaction management statements
ODBC Non-cursor statements
ODBC Cursor statements
ODBC Database stored procedures
238 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
DBHandle
DBHandle takes a transaction object as a parameter and returns a long variable,
which is the handle to the database for the transaction. This handle is actually
the connection handle PowerBuilder uses internally to communicate with the
database. You can use this returned long value in the ODBC DLLs and pass it
as one of the parameters in your function.
After you obtain the connection handle, you can use the ODBC SQLGetInfo
call to obtain the environment handle of the variable type HENV.
Example This example illustrates how to use DBHandle. As with other examples,
assume a successful connection has occurred using the default transaction
object (SQLCA).
// Define a variable to hold the DB connection
// handle
long ODBCConnectionHandle
// Go get the handle.
ODBCConnectionHandle = SQLCA.DBHandle( )
// Now that you have the ODBC connection pointer,
// call the DLL function.
MyDLLFunction(ODBCConnectionHandle, parm1, parm2)
In your DLL, cast the incoming connection handle of the type HDBC:
MyDLLFunction(long 1ODBCConnectionHandle,
parm1_type parm1,
parm2_type Parm2, ...)
{
HDBC * pDatabase;
pDatabase = (HDBC *) 1ODBCConnectionHandle;
// ODBC functions can be called using pDatabase.
}
See also ODBC Using escape clauses
240 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
Isolation feature ODBC uses the isolation feature to support assorted database lock options. In
PowerBuilder, you can use the Lock property of the transaction object to set the
isolation level when you connect to the database.
The following example shows how to set the Lock property to RU (Read
uncommitted):
// Set the lock property to read uncommitted
// in the default transaction object SQLCA.
SQLCA.Lock = "RU"
PowerBuilder uses the ODBC API call SQ2.SetConnectOption
(SetIsolationLevel) to set the isolation level. The lock value is passed to the
function as a 32-bit mask.
Example 1 This script uses embedded SQL to connect to a database and attempts to insert
a row in the ORDER_HEADER table and a row in the ORDER_ITEM table.
The script then executes a COMMIT or ROLLBACK depending on the success
of all statements in the script.
// Set the SQLCA connection properties.
SQLCA.DBMS = "ODBC"
242 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This example uses scripts for the Open and Close events for a window and the
Clicked event for a CommandButton to illustrate how you can manage
transactions for a DataWindow control. Assume a window contains a
DataWindow control dw_1 and a CommandButton Cb_Update. Also assume
the user enters data in dw_1 and then clicks the Cb_Update button to update
the database with the data.
The window OPEN event script:
// Set the transaction object properties
// and connect to the database.
// Set the SQLCA connection properties.
SQLCA.DBMS = "ODBC"
SQLCA.DBParm = "connectstring = 'DSN = orders'"
// Connect to the database.
CONNECT USING SQLCA;
// Tell the DataWindow which transaction object
// to use.
dw_1.SetTransObject(sqlca)
The CommandButton CLICKED event script:
// Declare ReturnValue an integer.
integer ReturnValue
ReturnValue = dw_1.Update( )
// Test to see if updates were successful.
if ReturnValue = -1 then
// Updates were not successful. Since we used
// SetTransObject, roll back any changes made
// to the database.
ROLLBACK USING SQLCA;
else
// Updates were successful. Since we used
// SetTransObject, commit any changes made
// to the database.
COMMIT USING SQLCA;
end if
The window CLOSE event script:
// Disconnect from the database.
DISCONNECT USING SQLCA;
244 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
ODBC SELECT
The SELECT statement contains input and output variables.
• Input variables are passed to the database as part of the execution, and
the substitution is as described for DELETE, INSERT, and UPDATE.
• Output variables return values based on the result of the SELECT
statement.
Example 1 Assume you enter the following statement:
SELECT emp_name, emp_salary
INTO :emp_name_var, :emp_salary_var
FROM employee WHERE emp_id = :emp_id_var;
Assume the value for emp_id_var is 691 as in the previous example. When the
SELECT statement executes, the database receives this command:
SELECT emp_name, emp_salary
FROM employee WHERE emp_id = 691;
If no errors are returned when the statement executes, data locations are bound
internally for the result fields. The data returned into these locations is
converted if necessary, and the appropriate PowerScript variables are set to
those values.
Example 2 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. It also
assumes the data type of the emp_id column in the employee table is
CHARACTER[10]. The user enters an employee ID into the single line edit
field sle_Emp and clicks the button Cb_Delete.
The script for the Clicked event in the CommandButton Cb_Delete is:
// Make sure we have a value.
if sle_Emp.text <> "" then
// Since we have a value, let's try to delete
// it.
DELETE FROM employee
WHERE emp_id = :sle_Emp.text;
// Test to see if the DELETE worked.
if SQLCA.sqlcode = 0 then
// It seems to have worked; let user know.
MessageBox("Delete",&
"The delete has been successfully "&
246 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
+"processed!")
else
// It didn't work.
MessageBox("Error", &
"The delete failed. Employee ID "&
+"is not valid.")
end if
else
// No input value. Prompt user.
MessageBox("Error", &
"An employee ID is required for "&
+"delete!")
end if
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 3 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. The user
wants to extract rows from the employee table and insert them into the table
named extract_employees. The extraction occurs when the user clicks the
button Cb_Extract. The boolean variable YoungWorkers is set to TRUE or
FALSE elsewhere in the application.
The script for the Clicked event for the CommandButton Cb_Extract is:
integer EmployeeAgeLowerLimit
integer mployeeAgeUpperLimit
// Do they have young workers?
if (YoungWorkers = TRUE) then
// Yes - set the age limit in the YOUNG range.
// Assume no employee is under legal working age.
EmployeeAgeLowerLimit = 16
// Pick an upper limit.
EmployeeAgeUpperLimit = 42
else
// No - set the age limit in the OLDER range.
EmployeeAgeLowerLimit = 43
// Pick an upper limit that includes all employees.
EmployeeAgeUpperLimit = 200
end if
INSERT INTO extract_employees(emp_id,emp_name)
SELECT emp_id, emp_name FROM employee
WHERE emp_age >= :EmployeeAgeLowerLimit
AND emp_age <= :EmployeeAgeUpperLimit;
248 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
For example, if you expect only a single row to exist in the employee table for
each emp_id, use a singleton SELECT statement. In a singleton SELECT, you
specify the SELECT statement and destination variables in one concise SQL
statement:
SELECT emp_name, emp_salary
INTO :emp_name_var, :emp_salary_var
FROM employee WHERE emp_id = :emp_id_var;
However, if the SELECT may return multiple rows, you must:
1 Declare a cursor.
2 Open it (which conceptually executes the SELECT).
3 Fetch rows as needed.
4 Close the cursor.
Declaring and opening Declaring a cursor is tightly coupled with the OPEN statement. The
a cursor DECLARE specifies the SELECT statement to be executed, and the OPEN
actually executes it.
Declaring a cursor is similar to declaring a variable. A cursor declaration is a
nonexecutable statement just like a variable declaration. The first step in
declaring a cursor is to define how the result set looks. To do this, you need a
SELECT statement, and since you must refer to the result set in subsequent
SQL statements, you must associate the result set with a logical name.
Example
Assume the SingleLineEdit sle_1 contains the state code for the retrieval:
// Declare cursor emp_curs for employee table
// retrieval.
DECLARE emp_curs CURSOR FOR
SELECT emp_id, emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
// Declare local variables for retrieval.
string emp_id_var
string emp_name_var
// Execute the SELECT statement with
// the current value of sle_1.text.
OPEN emp_curs;
// At this point, if there are no errors,
// the cursor is available for further
// processing.
Scrolling and locking Use the DBParm parameters CursorScroll and CursorLock to specify the
scrolling and locking options.
Note Not all DBMSs support these scrolling and locking options.
Fetching rows The ODBC interface supports the following FETCH statements. You can use
them if they are supported by your backend DBMS.
• FETCH NEXT
• FETCH FIRST
• FETCH PRIOR
• FETCH LAST
See also ODBC FETCH FIRST, FETCH PRIOR, and FETCH LAST
250 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
Closing the cursor The CLOSE statement terminates processing for the specified cursor. CLOSE
releases resources associated with the cursor, and subsequent references to that
cursor are allowed only if another OPEN is executed. Although you can have
multiple cursors open at the same time, you should close the cursors as soon as
possible for efficiency reasons.
See also ODBC FETCH NEXT
ODBC Update
After a FETCH statement completes successfully, you are positioned on a
current row within the cursor. At this point, you can execute an UPDATE or
DELETE statement using the WHERE CURRENT OF cursor_name syntax to
update or delete the row. PowerBuilder enforces the cursor update restrictions
of the backend database, and violations will result in an execution error.
Example This cursor example illustrates how to loop through a result set. It assumes that
the default transaction object (SQLCA) has been assigned valid values and a
successful CONNECT has been executed. The statements retrieve rows from
the employee table, and then display a message box with the employee name
for each row that is found.
// Declare the emp_curs.
DECLARE emp_curs CURSOR FOR
SELECT emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
// Declare a destination variable for employee
// names.
string emp_name_var
// Execute the SELECT statement with the
// current value of sle_1.text.
OPEN emp_curs;
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
252 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
ODBC Retrieval
PowerBuilder uses a construct similar to cursors to support retrieval using
database stored procedures. PowerBuilder supports four embedded SQL
statements that involve database stored procedures:
• DECLARE procedure_name PROCEDURE FOR ...
• EXECUTE procedure_name
• FETCH procedure_name INTO ...
• CLOSE procedure_name
See also ODBC DECLARE and EXECUTE
ODBC EXECUTE
ODBC FETCH
ODBC CLOSE
254 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
If the stored procedure contains result sets, you must fetch the result sets first.
If the stored procedure has a return value and you want to obtain it, use the
format RC=procedure_name:
DECLARE sp_duration PROCEDURE FOR
RC=pr_date_diff_prd_ken
@var_date_1 = :ad_start,
@var_date_2 = :ad_end,
@rtn_diff_prd = :ls_duration OUTPUT;
ODBC FETCH
To access rows returned in a result set, use the FETCH statement the same way
you use it for cursors. The FETCH statement can be executed after any
successful EXECUTE statement for a procedure that returns a result set.
Example FETCH emp_proc INTO :emp_name_var;
Since PowerBuilder cannot determine at compile time what result set will be
returned when a database stored procedure executes, you must code FETCH
statements so that the stored procedure exactly matches the format of the result
set during execution. Assume you coded the second FETCH statement in the
example above as:
FETCH emp_proc INTO :var1, :var2, :var3;
The statement compiles without errors. However, you will get an execution
error indicating that the number of columns in the FETCH statement does not
match the number of columns in the result set.
See also ODBC EXECUTE
ODBC FETCH NEXT
ODBC FETCH FIRST, FETCH PRIOR, and FETCH LAST
256 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
ODBC CLOSE
If a database stored procedure returns a result set, you must close the stored
procedure when processing is complete. The procedure remains open until you
close it, execute a COMMIT or ROLLBACK, or end the database connection.
ODBC EXECUTE
Database stored procedures that perform only updates and do not return a result
set are handled in much the same way as procedures that return a result set. The
only difference is that after the EXECUTE procedure_name statement
executes, no result set is pending, so a CLOSE statement is not required.
Using the SQLCode If a specific procedure can never return a result set, only the EXECUTE
property statement is required. If a procedure may or may not return a result set, you can
test the SQLCode property of the referenced transaction object for +100 (the
code for NOT FOUND) after the EXECUTE.
The possible values for SQLCode after an EXECUTE are:
Return code Means
0 The EXECUTE was successful and a result set is pending.
Regardless of the number of FETCH statements executed, the
procedure must be explicitly closed with a CLOSE statement.
Fetched row not found.
+100 Fetched row not found.
-1 The EXECUTE was not successful and no result set was
returned.
Example 1 This example illustrates how to execute a stored procedure that does not return
a result set. It assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has been executed.
// good_employee is a database stored procedure.
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This example illustrates how to pass parameters to a database stored procedure.
It assumes the default transaction object (SQLCA) has been assigned valid
values and a successful CONNECT has been executed. Emp_id_var was set to
691 elsewhere.
// get_employee is a database stored procedure.
// Declare the procedure.
DECLARE get_emp_proc PROCEDURE FOR
get_employee @emp_id_parm = :emp_id_var;
// Declare a destination variable for emp_name.
string emp_name_var
// Execute the stored procedure using the
// current value for emp_id_var.
EXECUTE get_emp_proc;
// Test return code to see if it worked.
if SQLCA.sqlcode = 0 then
// Since we got a row, fetch it and display it.
FETCH get_emp_proc INTO :emp_name_var;
// Display the employee name.
MessageBox("Got my employee!",emp_name_var)
// You are all done, so close the procedure.
CLOSE Get_emp_proc;
258 PowerBuilder
CHAPTER 16 Using Embedded SQL with ODBC
end if
260 PowerBuilder
CHAPTER 17 Using Embedded SQL with JDBC
When you use the JDBC interface to connect to a database, you can use
embedded SQL in your scripts.
262 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
About this chapter When you create scripts for a PowerBuilder application, you can use embedded
SQL statements in the script to perform operations on the database. The
features supported when you use embedded SQL depend on the DBMS to
which your application connects.
Overview When you use the PowerBuilder OLE DB interface to connect to a backend
database, you can use embedded SQL in your scripts.
You can embed the following types of SQL statements in scripts and user-
defined functions if the OLE DB driver you are using and the backend DBMS
you are accessing supports this functionality. (Not all backend databases
support cursor statements and database stored procedures.)
• Transaction management statements
• Non-cursor statements
• Cursor statements
• Database stored procedures
OLE DB Programming OLE DB is a set of COM (Component Object Model) interfaces that provide
Models uniform access to data stored in multiple, diverse data sources. These data
sources also enable applications to provide additional database services.
When you use embedded SQL, PowerBuilder makes the required calls to the
backend database. Therefore, you do not need to know anything about the OLE
DB interface to use embedded SQL with PowerBuilder.
See also Chapter 4, Using the OLE DB Interface
OLE DB SQL support
OLE DB Transaction management statements
OLE DB Non-cursor statements
OLE DB Cursor statements
OLE DB Database stored procedures
264 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
pIDBCreateSession->CreateSession(NULL, //pUnkOuter
IID_IDBCreateCommand, //riid
ppUnkSession //ppSession
);
}
Example 2 This example illustrates how to use DBHandle to get an OLE DB session
object.
// Before connection, set DBParm ReturnCommandHandle=1
...
SQLCA.DBParm = "ReturnCommandHandle = 1"
CONNECT;
// After successful connection
// Define a variable to hold the DB connection handle.
long OleDbCnnInterface
// Get OLE DB session object
OleDbCnnInterface = SQLCA.DBHandle()
// Now you have the OLE DB session object,
// call the DLL function.
MyDLLFunction(OleDbCnnInterface, parm1, parm2)
// In your DLL, cast the incoming handle to
// IUnknown* interface
MyDLLFunction(long OleDbCnnInterface,
parm1_type parm1,
parm2_type Parm2, ...)
{
IUnknown* pUnkSession = &
(IUnknown*)OleDbCnnInterface;
IDBCreateCommand * pIDBCreateCommand = NULL;
pUnkSession->QueryInterface &
(IID_IDBCreateCommand,
(void**)&pIDBCreateCommand));
With the IDBCreateCommand interface used by the PowerBuilder OLE DB
interface, you can create your own command object. Your command object and
the PowerBuilder command object will be in the same transaction scope.
See also OLE DB Using ODBC escape Sequences
266 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
Note For maximum portability, you should use escape sequences in your
applications.
Syntax For example, PowerBuilder uses the date, time, and timestamp escape clauses
as the default formats for data manipulation. The syntax for each of these
escape clauses is:
{ d yyyy-mm-dd }
{ t hh:mm:ss }
{ ts yyyy-mm-dd hh:mm:ss:[fff[fff]] }
Example Each of the following statements updates employee Henry Jones's start time in
the Employee table. The first statement uses the escape clause, and the second
statement uses native syntax for a time column:
UPDATE Employee
SET start_time = {t 08:30:00}
WHERE emp_name = "Henry Jones"
UPDATE Employee
SET start_time = (08:30:00)
WHERE emp_name = "Henry Jones"
268 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
Isolation feature OLE DB uses the isolation feature to support assorted database lock options.
In PowerBuilder, you can use the Lock property of the transaction object to set
the isolation level when you connect to the database.
The following example shows how to set the Lock property to RU (Read
uncommitted):
// Set the lock property to read uncommitted
// in the default transaction object SQLCA.
SQLCA.Lock = "RU"
Example 1 This script uses embedded SQL to connect to a database and attempts to insert
a row in the ORDER_HEADER table and a row in the ORDER_ITEM table.
The script then executes a COMMIT or ROLLBACK depending on the success
of all statements in the script.
// Set the SQLCA connection properties.
SQLCA.DBMS = "OLE DB"
SQLCA.DBParm = "PROVIDER='SAOLEDB.10',DATASOURCE= &
'SQL Anywhere 10 Demo'”
// Connect to the database.
CONNECT USING SQLCA;
// Insert a row into the ORDER_HEADER table.
INSERT INTO ORDER_HEADER (ORDER_ID,CUSTOMER_ID)
VALUES (7891, 129);
// Test return code for ORDER_HEADER insertion.
// A ROLLBACK is required only if the first row
// was inserted successfully.
if SQLCA.sqlcode = 0 then
// Since the ORDER_HEADER is inserted,
// try to insert ORDER_ITEM.
INSERT INTO ORDER_ITEM
(ORDER_ID, ITEM_NBR, PART_NBR, QTY)
VALUES (7891, 1, '991PLS', 456);
// Test return code for ORDER_ITEM insertion.
if SQLCA.sqlcode = -1 then
// If insert failed, ROLLBACK insertion of
// ORDER_HEADER.
ROLLBACK USING SQLCA;
end if
end if
// Disconnect from the database.
DISCONNECT USING SQLCA;
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
270 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
Example 2 This example uses scripts for the Open and Close events for a window and the
Clicked event for a CommandButton to illustrate how you can manage
transactions for a DataWindow control. Assume a window contains a
DataWindow control dw_1 and a CommandButton Cb_Update. Also assume
the user enters data in dw_1 and then clicks the Cb_Update button to update
the database with the data.
The window OPEN event script:
// Set the transaction object properties
// and connect to the database.
// Set the SQLCA connection properties.
SQLCA.DBMS = "OLE DB"
SQLCA.DBParm = "PROVIDER='SAOLEDB.10',DATASOURCE= &
'SQL Anywhere 10 Demo'”
// Connect to the database.
CONNECT USING SQLCA;
// Tell the DataWindow which transaction object
// to use.
dw_1.SetTransObject(sqlca)
The CommandButton CLICKED event script:
// Declare ReturnValue an integer.
integer ReturnValue
ReturnValue = dw_1.Update( )
// Test to see if updates were successful.
if ReturnValue = -1 then
// Updates were not successful. Since we used
// SetTransObject, roll back any changes made
// to the database.
ROLLBACK USING SQLCA;
else
// Updates were successful. Since we used
// SetTransObject, commit any changes made
// to the database.
COMMIT USING SQLCA;
end if
The window CLOSE event script:
// Disconnect from the database.
DISCONNECT USING SQLCA;
272 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
OLE DB SELECT
The SELECT statement contains input and output variables.
• Input variables are passed to the database as part of the execution, and the
substitution is as described for DELETE, INSERT, and UPDATE.
• Output variables return values based on the result of the SELECT
statement.
Example 1 Assume you enter the following statement:
SELECT emp_name, emp_salary
INTO :emp_name_var, :emp_salary_var
FROM employee WHERE emp_id = :emp_id_var;
In this example, emp_id_var, emp_salary_var, and emp_name_var are
PowerScript variables defined within the scope of the script containing the
SELECT statement, and emp_id_var is an input variable and is processed as
described in the DELETE example above.
Both emp_name_var and emp_salary_var are output variables that will be used
to return values from the database. The data types of emp_name_var and
emp_salary_var should be the PowerScript data types that best match the data
type in the database. When the data types do not match perfectly, PowerBuilder
converts them.
Assume the value for emp_id_var is 691 as in the previous example. When the
SELECT statement executes, the database receives this command:
SELECT emp_name, emp_salary
FROM employee WHERE emp_id = 691;
If no errors are returned when the statement executes, data locations are bound
internally for the result fields. The data returned into these locations is
converted if necessary, and the appropriate PowerScript variables are set to
those values.
Example 2 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. It also
assumes the data type of the emp_id column in the employee table is
CHARACTER[10]. The user enters an employee ID into the single line edit
field sle_Emp and clicks the button Cb_Delete.
The script for the Clicked event in the CommandButton Cb_Delete is:
// Make sure we have a value.
if sle_Emp.text <> "" then
// Since we have a value, let's try to
// delete it.
DELETE FROM employee
WHERE emp_id = :sle_Emp.text;
// Test to see if the DELETE worked.
if SQLCA.sqlcode = 0 then
// It seems to have worked; let user know.
MessageBox("Delete",&
"The delete has been successfully "&
+"processed!")
else
// It didn't work.
MessageBox("Error", &
"The delete failed. Employee ID "&
+"is not valid.")
end if
else
// No input value. Prompt user.
MessageBox("Error", &
"An employee ID is required for "&
+"delete!")
end if
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 3 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. The user
wants to extract rows from the employee table and insert them into the table
named extract_employees. The extraction occurs when the user clicks the
button Cb_Extract. The boolean variable YoungWorkers is set to TRUE or
FALSE elsewhere in the application.
The script for the Clicked event for the CommandButton Cb_Extract is:
integer EmployeeAgeLowerLimit
integer EmployeeAgeUpperLimit
274 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
276 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
OPEN emp_curs;
// At this point, if there are no errors,
// the cursor is available for further
// processing.
Fetching rows The PowerBuilder OLE DB interface supports FETCH statements.
See also OLE DB FETCH NEXT
Closing the cursor The CLOSE statement terminates processing for the specified cursor. CLOSE
releases resources associated with the cursor, and subsequent references to that
cursor are allowed only if another OPEN is executed. Although you can have
multiple cursors open at the same time, you should close the cursors as soon as
possible for efficiency reasons.
OLE DB Retrieval
PowerBuilder uses a construct similar to cursors to support retrieval using
database stored procedures. PowerBuilder supports four embedded SQL
statements that involve database stored procedures:
• DECLARE procedure_name PROCEDURE FOR ...
• EXECUTE procedure_name
• FETCH procedure_name INTO ...
• CLOSE procedure_name
See also OLE DB DECLARE and EXECUTE
278 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
OLE DB EXECUTE
OLE DB FETCH
OLE DB CLOSE
EXECUTE emp_proc;
Example 2 This example declares a stored procedure with two input and one output
parameters:
DECLARE sp_duration PROCEDURE FOR pr_date_diff_prd_ken
@var_date_1 = :ad_start,
@var_date_2 = :ad_end,
@rtn_diff_prd = :ls_duration OUTPUT;
If the stored procedure contains result sets, you must fetch the result sets first.
If the stored procedure has a return value and you want to obtain it, use the
format RC=procedure_name:
DECLARE sp_duration PROCEDURE FOR&
RC=pr_date_diff_prd_ken
@var_date_1 = :ad_start,
@var_date_2 = :ad_end,
@rtn_diff_prd = :ls_duration OUTPUT;
See also OLE DB EXECUTE
OLE DB FETCH
To access rows returned in a result set, use the FETCH statement the same way
you use it for cursors. The FETCH statement can be executed after any
successful EXECUTE statement for a procedure that returns a result set.
Example FETCH emp_proc INTO :emp_name_var;
Since PowerBuilder cannot determine at compile time what result set will be
returned when a database stored procedure executes, you must code FETCH
statements so that the stored procedure exactly matches the format of the result
set during execution. Assume you coded the second FETCH statement in the
example above as:
FETCH emp_proc INTO :var1, :var2, :var3;
280 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
The statement compiles without errors. However, you will get an execution
error indicating that the number of columns in the FETCH statement does not
match the number of columns in the result set.
See also OLE DB EXECUTE
OLE DB FETCH NEXT
OLE DB CLOSE
If a database stored procedure returns a result set, you must close the stored
procedure when processing is complete. The procedure remains open until you
close it, execute a COMMIT or ROLLBACK, or end the database connection.
OLE DB EXECUTE
Database stored procedures that perform only updates and do not return a result
set are handled in much the same way as procedures that return a result set. The
only difference is that after the EXECUTE procedure_name statement
executes, no result set is pending, so a CLOSE statement is not required.
Using the SQLCode If a specific procedure can never return a result set, only the EXECUTE
property statement is required. If a procedure may or may not return a result set, you can
test the SQLCode property of the referenced transaction object for +100 (the
code for NOT FOUND) after the EXECUTE.
The possible values for SQLCode after an EXECUTE are:
Example 1 This example illustrates how to execute a stored procedure that does not return
a result set. It assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has been executed.
// good_employee is a database stored procedure.
// Declare the procedure.
DECLARE good_emp_proc PROCEDURE
FOR good_employee;
// Execute it.
EXECUTE good_emp_proc;
// Test return code. Allow for +100 since you
// do not expect a result set.
if SQLCA.sqlcode = -1 then
// Issue an error message since it failed.
MessageBox("Stored Procedure Error!", &
SQLCA.sqlerrtext)
end if
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This example illustrates how to pass parameters to a database stored procedure.
It assumes the default transaction object (SQLCA) has been assigned valid
values and a successful CONNECT has been executed. Emp_id_var was set to
691 elsewhere.
// get_employee is a database stored procedure.
// Declare the procedure.
DECLARE get_emp_proc PROCEDURE FOR
get_employee @emp_id_parm = :emp_id_var;
// Declare a destination variable for emp_name.
282 PowerBuilder
CHAPTER 18 Using Embedded SQL with OLE DB
string emp_name_var
// Execute the stored procedure using the
// current value for emp_id_var.
EXECUTE get_emp_proc;
// Test return code to see if it worked.
if SQLCA.sqlcode = 0 then
// Since we got a row, fetch it and display it.
FETCH get_emp_proc INTO :emp_name_var;
// Display the employee name.
MessageBox("Got my employee!",emp_name_var)
// You are all done, so close the procedure.
CLOSE Get_emp_proc;
end if
284 PowerBuilder
CHAPTER 19 Using Embedded SQL with ADO.NET
When you use the ADO.NET interface to connect to a database, you can use
embedded SQL in your scripts.
286 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
About this chapter When you create scripts for a PowerBuilder application, you can use embedded
SQL statements in the script to perform operations on the database. The
features supported when you use embedded SQL depend on the DBMS to
which your application connects.
Overview When you use the SAP Adaptive Server Enterprise interface, you can use
embedded SQL in your scripts. You can embed the following types of SQL
statements in scripts and user-defined functions:
• Transaction management statements
• Non-cursor statements
• Cursor statements
• Database stored procedures
Client Library API The SAP Adaptive Server Enterprise database interface uses the Client Library
(CT-Lib) application programming interface (API) to interact with the
database.
When you use embedded SQL, PowerBuilder makes the required calls to the
API. Therefore, you do not need to know anything about CT-Lib to use
embedded SQL in PowerBuilder.
See also Chapter 8, Using Adaptive Server Enterprise
SAP Adaptive Server Enterprise SQL functions
SAP Adaptive Server Enterprise Transaction management statements
SAP Adaptive Server Enterprise Non-cursor statements
SAP Adaptive Server Enterprise Cursor statements
SAP Adaptive Server Enterprise Database stored procedures
SAP Adaptive Server Enterprise Name qualification
288 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
Using DBHandle to DBHandle takes a transaction object as a parameter and returns a long variable,
obtain the which is the CS_CONNECTION pointer that PowerBuilder uses internally to
CS_CONNECTION
pointer communicate with the database. You can pass this value as one of the
parameters to your external function.
This example shows how to use DBHandle. Assume a successful connection
has occurred using the default transaction object (SQLCA):
// Define a variable to hold our DB handle.
long SQLServerHandle
// Go get the handle.
SQLServerHandle = SQLCA.DBHandle( )
// Now that you have the CS_CONNECTION pointer,
// call the DLL function.
MyDLLFunction( SQLServerHandle, parm1, parm2, ... )
In your DLL, cast the incoming long value into a pointer to a
CS_CONNECTION structure:
MyDLLFunction( long 1SQLServerHandle,
parm1_type parm1,
parm2_type Parm2, ... )
{
CS_CONNECTION * pConnect;
pConnect = (CS_CONNECTION *) 1SQLServerHandle;
// CT-LIB functions can be called using pConnect.
}
Obtaining the Within your external function, you can obtain the CS_CONTEXT pointer with
CS_CONTEXT the following function call:
pointer
CS_RETCODE RC;
CS_CONNECTION * PConnect;
CS_INT outlen;
CS_CONTEXT * pContext;
rc = ct_con_props (pConnect,CS_GET,CS_PARENT_HANDLE,
(CS_VOID *) &pContext, CS_UNUSED,
&outlen);
Allocating a new Likewise, you can allocate a new command pointer with the following code:
command pointer
CS_COMMAND * pCommand;
rc = ct_cmd_alloc(pConnect, &pCommand);
290 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
Statement Description
COMMIT COMMIT terminates the logical unit of work, guarantees that all
changes made to the database since the beginning of the current
unit of work become permanent, and starts a new logical unit of
work.
If AutoCommit is false (the default), a COMMIT
TRANSACTION executes, then a BEGIN TRANSACTION
executes to start a new logical unit of work.
If AutoCommit is true, the COMMIT is issued but has no effect
because all previous database changes were already
automatically committed.
DISCONNECT Terminates a successful connection. DISCONNECT
automatically executes a COMMIT to guarantee that all changes
made to the database since the beginning of the current unit of
work are committed.
If AutoCommit is false, a COMMIT TRANSACTION executes
automatically to guarantee that all changes made to the database
since the beginning of the current logical unit of work are
committed.
ROLLBACK ROLLBACK terminates a logical unit of work, undoes all
changes made to the database since the beginning of the logical
unit of work, and starts a new logical unit of work.
If AutoCommit is false, a ROLLBACK TRANSACTION
executes, then a BEGIN TRANSACTION executes to start a new
logical unit of work.
If AutoCommit is true, a ROLLBACK TRAN executes but has
no effect because all previous database changes were already
committed.
292 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This example uses the scripts for the Open and Close events in a window and
the Clicked event in a CommandButton to illustrate how you can manage
transactions in a DataWindow control. Assume that the window contains a
DataWindow control dw_1 and that the user enters data in dw_1 and then clicks
the Cb_Update button to send the data to the database.
Since this script uses SetTransObject to connect to the database, the
programmer is responsible for managing the transaction.
The window OPEN event script:
// Set the transaction object properties
// and connect to the database.
// Set the SQLCA connection properties.
SQLCA.DBMS = "SYC"
SQLCA.servername = "SERVER24"
SQLCA.database = "ORDERS"
SQLCA.logid = "JPL"
SQLCA.logpass = "TREESTUMP"
294 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
296 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
Assume the value for emp_id_var is 691 as in the previous example. When the
SELECT statement executes, the database receives the following statement:
SELECT emp_name, emp_salary
FROM employee WHERE emp_id = 691;
If the statement executes with no errors, data locations for the result fields are
bound internally. The data returned into these locations is then converted as
necessary and the appropriate PowerScript data variables are set to those
values.
Example 2 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. It also
assumes the data type of the emp_id column in the employee table is
CHARACTER[10].
The user enters an employee ID into the single line edit field sle_Emp and
clicks the button Cb_Delete to delete the employee.
The script for the Clicked event in the CommandButton Cb_Delete is:
// Make sure we have a value.
if sle_Emp.text <> "" then
// Since we have a value, try to delete it.
DELETE FROM employee
WHERE emp_id = :sle_Emp.text;
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 3 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. The user
wants to extract rows from the employee table and insert them into the table
named extract_employees. The extraction occurs when the user clicks the
button Cb_Extract. The boolean variable YoungWorkers is set to TRUE or
FALSE elsewhere in the application.
The script for the Clicked event for the CommandButton Cb_Extract is:
integer EmployeeAgeLowerLimit
integer EmployeeAgeUpperLimit
// Do they have young workers?
if ( YoungWorkers = TRUE ) then
// Yes - set the age limit in the YOUNG range.
// Assume no employee is under legal working age.
EmployeeAgeLowerLimit = 16
298 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
300 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
Multiple cursors
The CT-Lib API lets you declare and open multiple cursors without having to
open additional database connections.
Example Assume the SingleLineEdit sle_1 contains the state code for the retrieval:
// Declare cursor emp_curs for employee table retrieval.
DECLARE emp_curs CURSOR FOR
SELECT emp_id, emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
// Declare local variables for retrieval.
string emp_id_var
string emp_name_var
// Execute the SELECT statement with
// the current value of sle_1.text.
OPEN emp_curs;
// At this point, if there are no errors,
// the cursor is available for further
// processing.
Fetching rows In the singleton SELECT, you specify variables to hold the values for the
columns within the selected row. The FETCH statement syntax is similar to the
syntax of the singleton SELECT. Values are returned INTO a specified list of
variables.
This example continues the previous example by retrieving some data:
// Go get the first row from the result set.
FETCH emp_curs INTO :emp_id_var, :emp_name_var;
If at least one row can be retrieved, this FETCH places the values of the emp_id
and emp_name columns from the first row in the result set into the PowerScript
data variables emp_id_var and emp_name_var. Executing another FETCH
statement will place the variables from the next row into specified variables.
FETCH statements typically occur in a loop that processes several rows from
a result set (one row at a time): fetch the row, process the variables, and then
fetch the next row.
Example This cursor example illustrates how you can loop through a result set. Assume
the default transaction object (SQLCA) has been assigned valid values and a
successful CONNECT has been executed.
The statements retrieve rows from the employee table and then display a
message box with the employee name in each row that is found.
// Declare the emp_curs.
DECLARE emp_curs CURSOR FOR
SELECT emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
// Declare a destination variable for employee
// names.
string emp_name_var
// Execute the SELECT statement with the
// current value of sle_1.text.
OPEN emp_curs;
// Fetch the first row from the result set.
FETCH emp_curs INTO :emp_name_var;
// Loop through result set until exhausted.
DO WHILE SQLCA.sqlcode = 0
// Pop up a message box with the employee name.
MessageBox("Found an employee!",emp_name_var)
// Fetch the next row from the result set.
FETCH emp_curs INTO :emp_name_var;
LOOP
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
302 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
304 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
• CLOSE procedure_name
See also SAP Adaptive Server Enterprise DECLARE and EXECUTE
SAP Adaptive Server Enterprise FETCH
SAP Adaptive Server Enterprise CLOSE
306 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
EXECUTE emp_proc;
Note You can use this FETCH statement only to access values produced with
a SELECT statement in a database stored procedure. You cannot use the
FETCH statement to access computed rows.
Example 1 Database stored procedures can return multiple result sets. Assume you define
a database stored procedure proc2 as:
CREATE PROCEDURE proc2 AS
SELECT emp_name FROM employee
SELECT part_name FROM parts
PowerBuilder provides access to both result sets:
// Declare the procedure.
DECLARE emp_proc2 PROCEDURE FOR proc2;
// Declare some variables to hold results.
string emp_name_var
string part_name_var
// Execute the stored procedure.
EXECUTE emp_proc2;
// Loop through all rows in the first result
// set.
DO WHILE SQLCA.sqlcode = 0
// Fetch the next row from the first result set.
FETCH emp_proc2 INTO :emp_name_var;
LOOP
// At this point we have exhausted the first
// result set. After this occurs,
// PowerBuilder notes that there is another
308 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
Example 1 Assume the default transaction object (SQLCA) has been assigned valid values
and a successful CONNECT has been executed. Also assume the description
of the Adaptive Server Enterprise procedure good_employee is:
// Adaptive Server Enterprise good_employee
// stored procedure:
CREATE PROCEDURE good_employee AS
UPDATE employee
SET emp_salary=emp_salary * 1.1
WHERE emp_status = 'EXC'
This example illustrates how to execute a stored procedure that does not return
any result sets:
// Declare the procedure.
DECLARE good_emp_proc PROCEDURE
FOR good_employee;
// Execute it.
EXECUTE good_emp_proc;
// Test return code. Allow for +100 since you do
// not expect result sets.
if SQLCA.sqlcode = -1 then
// Issue error message since it failed.
MessageBox("Stored Procedure Error!", &
SQLCA.sqlerrtext)
end if
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 Assume the default transaction object (SQLCA) has been assigned valid values
and a successful CONNECT has been executed. Also assume the description
of the Adaptive Server Enterprise procedure get_employee is:
// Adaptive Server Enterprise get_employee
// stored procedure:
CREATE PROCEDURE get_employee @emp_id_parm
int AS SELECT emp_name FROM employee
WHERE emp_id = @emp_id_parm
This example illustrates how to pass parameters to a database stored procedure.
Emp_id_var has been set elsewhere to 691:
// Declare the procedure.
DECLARE get_emp_proc PROCEDURE FOR
get_employee @emp_id_parm = :emp_id_var;
// Declare a destination variable for emp_name.
string emp_name_var
// Execute the stored procedure using the
310 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
EXECUTE deptproc;
CHOOSE CASE SQLCA.sqlcode
CASE 0
// Execute successful. There is at least one
// result set. Loop to get the query result set
// from the table SELECT.
DO
FETCH deptproc INTO :fname, :lname, :dSalary;
CHOOSE CASE SQLCA.sqlcode
CASE 0
fetchcount++
CASE 100
MessageBox ("End of Result Set", &
string (fetchcount) " rows fetched")
CASE -1
MessageBox ("Fetch Failed", &
string (SQLCA.sqldbcode) " = " &
SQLCA.sqlerrtext)
END CHOOSE
LOOP WHILE SQLCA.sqlcode = 0
// Issue an extra FETCH to get the Return Value
// and Output Parameters.
FETCH deptproc INTO :rc, :dTotSal, :dAvgSal;
CHOOSE CASE SQLCA.sqlcode
CASE 0
MessageBox ("Fetch Return Value and Output" &
"Parms SUCCESSFUL", "Return Value is: " &
string (rc) &
"~r~nTotal Salary: " string (dTotSal) &
"~r~nAverage Sal: " string (dAvgSal))
CASE 100
MessageBox ("Return Value and Output Parms" &
"NOT FOUND", "")
CASE ELSE
MessageBox ("Fetch Return Value and Output" &
"Parms FAILED", "SQLDBCode is " &
string (SQLCA.sqldbcode) " = " &
SQLCA.sqlerrtext)
END CHOOSE
CLOSE deptproc;
CASE 100
// Execute successful; no result set.
// Do not try to close.
MessageBox ("Execute Successful", "No result set")
312 PowerBuilder
CHAPTER 20 Using Embedded SQL with SAP Adaptive Server Enterprise
CASE ELSE
MessageBox ("Execute Failed", &
string (SQLCA.sqldbcode) " = " &
SQLCA.sqlerrtext)
END CHOOSE
314 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
About this chapter When you create scripts for a PowerBuilder application, you can use embedded
SQL statements in the script to perform operations on the database. The
features supported when you use embedded SQL depend on the DBMS to
which your application connects.
Overview When you use the Informix IN9 database interface to connect to a database,
you can use embedded SQL in your scripts. You can embed the following types
of SQL statements in scripts and user-defined functions:
• Transaction management statements
• Non-cursor statements
• Cursor statements
• Database stored procedures
Informix API The Informix database interfaces use the Informix application programming
interface (API) to interact with the database.
When you use embedded SQL, PowerBuilder makes the required calls to the
API. Therefore, you do not need to know anything about the Informix API in
order to use embedded SQL in PowerBuilder.
See also Chapter 9, Using Informix
Informix transaction management statements
Informix non-cursor statements
Informix cursor statements
Informix database stored procedures
Informix name qualification
316 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
Statement Description
CONNECT Establishes the database connection. After you assign values to the
required properties of the transaction object, you can execute a
CONNECT. After this call completes successfully, PowerBuilder
issues a BEGIN WORK to start a logical unit of work for the
transaction.
COMMIT Terminates the logical unit of work, guarantees that all changes
made to the database since the beginning of the current unit of
work become permanent, and starts a new logical unit of work.
DISCONNECT Terminates a successful connection. DISCONNECT
automatically executes a COMMIT to guarantee that all changes
made to the database since the beginning of the current unit of
work are committed.
ROLLBACK Terminates a logical unit of work, undoes all changes made to the
database since the beginning of the logical unit of work, and starts
a new logical unit of work.
Example 1 This script uses embedded SQL to connect to a database and insert a row in
the ORDER_HEADER table and a row in the ORDER_ITEM table.
Depending on the success of the statements in the script, the script executes a
COMMIT or ROLLBACK:
// Set the SQLCA connection properties.
SQLCA.DBMS = "IN9"
SQLCA.database = "ORDERS"// Connect to the database.
318 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
// If insert failed
// ROLLBACK insertion of ORDER_HEADER.
ROLLBACK USING SQLCA;
end if
end if
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This example uses the scripts for the Open and Close events in a window and
the Clicked event in a CommandButton to illustrate how you can manage
transactions in a DataWindow control. Assume the window contains a
DataWindow control dw_1 and the user enters data in dw_1 and then clicks the
Cb_Update button to send the data to the database.
Since this script uses SetTransObject to connect to the database, the
programmer is responsible for managing the transaction.
Window Open event script // Set the transaction object
properties
// and connect to the database.
// Set the SQLCA connection properties.
SQLCA.DBMS = "IN9"
SQLCA.database = "ORDERS"
320 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
Informix SELECT
The SELECT statement contains input variables and output variables. Input
variables are passed to the database as part of the execution and the substitution
as described above for DELETE, INSERT, and UPDATE. Output variables are
used to return values based on the result of the SELECT statement.
Example 1 Assume you enter the following statement:
Assume the value for emp_id_var is 691 as in the previous example. When the
SELECT statement executes, the database receives the following statement:
SELECT emp_name, emp_salary
FROM employee WHERE emp_id = 691;
If no errors are returned on the execution, data locations are internally bound
for the result fields. The data returned into these locations is converted if
necessary and the appropriate PowerScript variables are set to those values.
Example 2 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. It also
assumes the data type of the emp_id column in the employee table is
CHARACTER[10].
The user enters an employee ID into the line edit sle_Emp and clicks the button
Cb_Delete to delete the employee.
The script for the Clicked event in the CommandButton Cb_Delete is:
// Make sure we have a value.
if sle_Emp.text <> "" then
322 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
// It didn't work.
MessageBox( "Error", &
"The delete failed. Employee ID is not valid.")
end if
else
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 3 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. The user
wants to extract rows from the employee table and insert them into the table
named extract_employees.
The extraction occurs when the user clicks the button Cb_Extract. The boolean
variable YoungWorkers is set to TRUE or FALSE elsewhere in the application.
The script for the Clicked event for the CommandButton Cb_Extract is:
integerEmployeeAgeLowerLimit
integerEmployeeAgeUpperLimit
324 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
326 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
Example This cursor example illustrates how you can loop through a result set. Assume
the default transaction object (SQLCA) has been assigned valid values and a
successful CONNECT has been executed.
The statements retrieve rows from the employee table and then display a
message box with the employee name in each row that is found.
// Declare the emp_curs
DECLARE emp_curs CURSOR FOR
SELECT emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
LOOP
328 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
330 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
The parameter references can take the form of any valid parameter string that
Informix accepts. PowerBuilder does not inspect the parameter list format
except for purposes of variable substitution. The USING clause is required
only if you are using a transaction object other than the default transaction
object (SQLCA).
Example Assume a stored procedure proc1 is defined as:
CREATE PROCEDURE proc1 AS
SELECT emp_name FROM employee
To declare that procedure for processing within PowerBuilder, enter:
DECLARE emp_proc PROCEDURE FOR proc1;
Note that this declaration is a nonexecutable statement, just like a cursor
declaration. Where cursors have an OPEN statement, procedures have an
EXECUTE statement.
When an EXECUTE statement is executed, the procedure is invoked. The
EXECUTE refers to the logical procedure name:
EXECUTE emp_proc;
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Issuing EXECUTE Use PowerBuilder embedded SQL syntax when you enter an embedded
statements EXECUTE statement in a script; do not enter the PROCEDURE keyword. Use
this syntax:
EXECUTE procedure_name;
Specify the EXECUTE statement the same way whether or not a stored
procedure takes arguments. The arguments used in the DECLARE statement
get passed automatically, without your having to state them in the EXECUTE
statement.
Informix FETCH
To access rows returned in a result set, you use the FETCH statement the same
way you use it for cursors. The FETCH statement can be executed after any
EXECUTE statement that refers to a procedure that returns a result set.
Informix syntax
PowerBuilder supports Informix syntax; however, the default syntax displayed
in the DataWindow painter is the most general syntax. You can leave the syntax
unchanged or edit the displayed syntax to conform to the Informix syntax rules.
If you do not change the syntax, PowerBuilder converts it to Informix syntax
before passing it to the Informix database.
Informix CLOSE
If a database stored procedure returns a result set, it must be closed when
processing is complete.
332 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
Example 1 This example illustrates how to execute a database stored procedure that does
not return a result set:
334 PowerBuilder
CHAPTER 21 Using Embedded SQL with Informix
336 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
About this chapter When you create scripts for a PowerBuilder application, you can use embedded
SQL statements in the script to perform operations on the database. The
features supported when you use embedded SQL depend on the DBMS to
which your application connects.
Overview When your PowerBuilder application connects to a SQL Server database, you
can use embedded SQL in your scripts. This interface uses the DB-Library
(DB-Lib) client API to access the database.
When you use the SQL Server database interface, you can embed the following
types of SQL statements in scripts and user-defined functions:
• Transaction management statements
• Non-cursor statements
• Cursor statements
• Database stored procedures
DB-Library API The Microsoft SQL Server database interface uses the DB-Library (DB-Lib)
application programming interface (API) to access the database. When you use
embedded SQL, PowerBuilder makes the required calls to the API. Therefore,
you do not need to know anything about DB-Lib to use embedded SQL in
PowerBuilder.
See also Microsoft SQL Server Functions
Microsoft SQL Server Transaction management statements
Microsoft SQL Server Non-cursor statements
Microsoft SQL Server Cursor statements
Microsoft SQL Server Using database stored procedures in DataWindow
objects
Microsoft SQL Server Name qualification
338 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
For example, assume that a certain condition within a trigger is not met and you
want to execute a ROLLBACK. Instead of coding the ROLLBACK directly in
the trigger, you should use RAISERROR and test for that particular return code
in the DBMS-specific return code (SQLDBCode) property within the
referenced transaction object.
See also Microsoft SQL Server Using CONNECT, COMMIT, DISCONNECT,
and ROLLBACK
340 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
Statement Description
ROLLBACK ROLLBACK terminates a logical unit of work, undoes all
changes made to the database since the beginning of the logical
unit of work, and starts a new logical unit of work.
If AutoCommit is false, a ROLLBACK TRANSACTION
executes, then a BEGIN TRANSACTION executes to start a
new logical unit of work. If AutoCommit is true, an error occurs
when a ROLLBACK executes.
342 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
Isolation feature SQL Server uses the isolation feature to support assorted database lock options.
In PowerBuilder, you can use the Lock property of the transaction object to set
the isolation level when you connect to a SQL Server database.
The following example shows how to set the Lock property to RU (Read
uncommitted):
// Set the lock property to read uncommitted
// in the default transaction object SQLCA.
SQLCA.Lock = "RU"
Example 1 This script uses embedded SQL to connect to a database and insert a row in
the ORDER_HEADER table and a row in the ORDER_ITEM table.
Depending on the success of the statements in the script, the script executes
either a COMMIT or a ROLLBACK.
// Set the SQLCA connection properties.
SQLCA.DBMS = "SQLServer"
SQLCA.servername = "SERVER24"
SQLCA.database = "ORDERS"
SQLCA.logid = "JPL"
SQLCA.logpass = "TREESTUMP"
// Connect to the database.
CONNECT USING SQLCA;
// Insert a row into the ORDER_HEADER table.
// A ROLLBACK is required only if the first row
// was inserted successfully.
INSERT INTO ORDER_HEADER (ORDER_ID,CUSTOMER_ID)
VALUES ( 7891, 129 );
// Test return code for ORDER_HEADER insertion.
if SQLCA.sqlcode = 0 then
// Since the ORDER_HEADER is inserted,
// try to insert ORDER_ITEM.
INSERT INTO ORDER_ITEM(ORDER_ID, ITEM_NBR,
PART_NBR, QTY)
VALUES ( 7891, 1, '991PLS', 456 );
// Test return code for ORDER_ITEM insertion.
if SQLCA.sqlcode = -1 then
// If insert failed.
// ROLLBACK insertion of ORDER_HEADER.
ROLLBACK USING SQLCA;
end if
end if
// Commit changes and disconnect from the database.
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This example uses the scripts for the Open and Close events in a window and
the Clicked event in a CommandButton to illustrate how you can manage
transactions in a DataWindow control. Assume that the window contains a
DataWindow control dw_1 and that the user enters data in dw_1 and then clicks
the Cb_Update button to send the data to the database.
Since this script uses SetTransObject to connect to the database, the
programmer is responsible for managing the transaction.
The window OPEN event script:
// Set the transaction object properties
// and connect to the database.
// Set the SQLCA connection properties.
SQLCA.DBMS = "SQLServer"
SQLCA.servername = "SERVER24"
SQLCA.database = "ORDERS"
SQLCA.logid = "JPL"
SQLCA.logpass = "TREESTUMP"
// Connect to the database.
CONNECT USING SQLCA;
// Tell the DataWindow which transaction object
// to use.
SetTransObject( dw_1, SQLCA )
The CommandButton CLICKED event script:
// Declare ReturnValue an integer.
integer ReturnValue
ReturnValue = Update( dw_1 )
// Test to see if updates were successful.
if ReturnValue = -1 then
// Updates were not successful. Since we used
// SetTransObject, rollback any changes made
// to the database.
ROLLBACK USING SQLCA;
else
344 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
When is this This variable substitution technique is used for all PowerScript variable types.
substitution technique When you use embedded SQL, precede all PowerScript variables with a colon
used?
( : ).
See also Microsoft SQL Server SELECT
Assume the value for emp_id_var is 691 as in the previous example. When the
SELECT statement executes, the database receives the following statement:
SELECT emp_name, emp_salary
FROM employee WHERE emp_id = 691;
346 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
If the statement executes with no errors, data locations for the result fields are
bound internally. The data returned into these locations is then converted as
necessary and the appropriate PowerScript data variables are set to those
values.
Example 2 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. It also
assumes the data type of the emp_id column in the employee table is
CHARACTER[10].
The user enters an employee ID into the single line edit field sle_Emp and
clicks the button Cb_Delete to delete the employee.
The script for the Clicked event in the CommandButton Cb_Delete is:
// Make sure we have a value.
if sle_Emp.text <> "" then
// Since we have a value, try to delete it.
DELETE FROM employee
WHERE emp_id = :sle_Emp.text;
// Test to see if the DELETE worked.
if SQLCA.sqlcode = 0 then
// It seems to have worked, let user know.
MessageBox( "Delete",&
"The delete has been successfully "&
+" processed!")
else
//It didn't work.
MessageBox( "Error", &
"The delete failed. Employee ID is not "&
+"valid.")
end if
else
// No input value. Prompt user.
MessageBox( "Error",&
"An employee ID is required for "&
+"delete!" )
end if
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 3 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. The user
wants to extract rows from the employee table and insert them into the table
named extract_employees. The extraction occurs when the user clicks the
button Cb_Extract. The boolean variable YoungWorkers is set to TRUE or
FALSE elsewhere in the application.
The script for the Clicked event for the CommandButton Cb_Extract is:
integer EmployeeAgeLowerLimit
integer EmployeeAgeUpperLimit
// Do they have young workers?
if ( YoungWorkers = TRUE ) then
// Yes - set the age limit in the YOUNG range.
// Assume no employee is under legal working age.
EmployeeAgeLowerLimit = 16
// Pick an upper limit.
EmployeeAgeUpperLimit = 42
else
// No - set the age limit in the OLDER range.
EmployeeAgeLowerLimit = 43
// Pick an upper limit that includes all
// employees.
EmployeeAgeUpperLimit = 200
end if
INSERT INTO extract_employee(emp_id,emp_name)
SELECT emp_id, emp_name FROM employee
WHERE emp_age >= :EmployeeAgeLowerLimit
AND emp_age <= :EmployeeAgeUpperLimit;
See also Microsoft SQL Server DELETE, INSERT, and UPDATE
348 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
• CLOSE cursor_name
350 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
If at least one row can be retrieved, this FETCH places the values of the emp_id
and emp_name columns from the first row in the result set into the PowerScript
data variables emp_id_var and emp_name_var. Executing another FETCH
statement will place the variables from the next row into specified variables.
FETCH statements typically occur in a loop that processes several rows from
a result set (one row at a time): fetch the row, process the variables, and then
fetch the next row.
What happens when FETCH returns +100 (not found) in the SQLCode property within the
the result set is referenced transaction object. This is an informational return code; -1 in
exhausted?
SQLCode indicates an error.
See also Microsoft SQL Server FETCH NEXT
Microsoft SQL Server FETCH FIRST, FETCH PRIOR, and FETCH
LAST
Example This cursor example illustrates how you can loop through a result set. Assume
the default transaction object (SQLCA) has been assigned valid values and a
successful CONNECT has been executed.
The statements retrieve rows from the employee table and then display a
message box with the employee name in each row that is found.
// Declare the emp_curs.
DECLARE emp_curs CURSOR FOR
SELECT emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
// Declare a destination variable for employee
// names.
string emp_name_var
// Execute the SELECT statement with the
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
352 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
Using AutoCommit Database stored procedures often create temporary table that hold rows
with database stored accumulated during processing. To create these tables, the stored procedure
procedures
executes SQL Data Definition Language (DDL) statements. Versions of SQL
Server prior to SQL Server 2000 do not allow you to execute DDL statements
within the scope of a transaction.
To execute SQL Server stored procedures that contain DDL statements
statements in SQL Server 7 and earlier, you must set the AutoCommit property
of the transaction object to true so PowerBuilder issues the statements outside
the scope of a transaction. However, if AutoCommit is set to true, you cannot
issue a ROLLBACK. Therefore, you should set AutoCommit back to false (the
default) immediately after completing the DDL operation.
When you change the value of AutoCommit from false to true, PowerBuilder
issues a COMMIT statement by default.
System database You can access system database stored procedures the same way you access
stored procedures user-defined stored procedures. You can use the DECLARE statement against
any procedure and can qualify procedure names if necessary.
See also Microsoft SQL Server Retrieval
Microsoft SQL Server Temporary tables
Microsoft SQL Server Update
Microsoft SQL Server Using database stored procedures in DataWindow
objects
Microsoft SQL Server Database stored procedures summary
354 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
356 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
You do not have to retrieve all the rows in a result set to close a request or
procedure.
Example 1 Assume the default transaction object (SQLCA) has been assigned valid values
and a successful CONNECT has been executed. Also assume the description
of the SQL Server procedure good_employee is:
// SQL Server good_employee stored procedure:
CREATE PROCEDURE good_employee AS
UPDATE employee
SET emp_salary=emp_salary * 1.1
WHERE emp_status = 'EXC'
This example illustrates how to execute a stored procedure that does not return
any result sets:
// Declare the procedure.
DECLARE good_emp_proc PROCEDURE
FOR good_employee;
// Execute it.
358 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
EXECUTE good_emp_proc;
// Test return code. Allow for +100 since you do
// not expect result sets.
if SQLCA.sqlcode = -1 then
// Issue error message since it failed.
MessageBox("Stored Procedure Error!", &
SQLCA.sqlerrtext)
end if
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 Assume the default transaction object (SQLCA) has been assigned valid values
and a successful CONNECT has been executed. Also assume the description
of the SQL Server procedure get_employee is:
// SQL Server get_employee stored procedure:
CREATE PROCEDURE get_employee @emp_id_parm
int AS SELECT emp_name FROM employee
WHERE emp_id = @emp_id_parm
This example illustrates how to pass parameters to a database stored procedure.
Emp_id_var has been set elsewhere to 691:
// Declare the procedure.
DECLARE get_emp_proc PROCEDURE FOR
get_employee @emp_id_parm = :emp_id_var;
// Declare a destination variable for emp_name.
string emp_name_var
// Execute the stored procedure using the
// current value for emp_id_var.
EXECUTE get_emp_proc;
// Test return code to see if it worked.
if SQLCA.sqlcode = 0 then
// Since we got a row, fetch it and display it.
FETCH get_emp_proc INTO :emp_name_var;
// Display the employee name.
MessageBox("Got my employee!",emp_name_var)
// You are all done, so close the procedure.
CLOSE Get_emp_proc;
end if
PowerBuilder also provides access to return values and output parameters. The
return values and output parameters are always in the last result set returned by
the stored procedure and they are in this order:
return value, output parm1, output parm 2 ...
Example 3 Assume the default transaction object (SQLCA) has been assigned valid values
and a successful CONNECT has been executed. Also assume the description
of the SQL Server procedure return is:
CREATE PROCEDURE emp_return @m1 int, @m2 int,
@resultp int output
AS SELECT @RESULTP = @m1*@m2
RETURN 0
where @m1, @m2, and @resultp are integers.
This example shows how PowerBuilder provides access to return values:
//Stored procedure syntax
CREATE PROCEDURE sp_outputs @ml int, @m2 int,
@result int output as SELECT
@result = @ml*@m2;
//Declare syntax in script.
DECLARE myproc PROCEDURE for sp_outputs @ml = 3,
@m2 = 3, @result = 0 output;
//Note: The parameters in the declare must match
//exactly the parameters in the sp.
EXECUTE myproc;
//Execute fetches needed until rc = 100
//then fetch output parameters.
int myresult
FETCH myproc into :myresult;
CLOSE myproc;
360 PowerBuilder
CHAPTER 22 Using Embedded SQL with Microsoft SQL Server
362 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
About this chapter When you create scripts for a PowerBuilder application, you can use embedded
SQL statements in the script to perform operations on the database. The
features supported when you use embedded SQL depend on the DBMS to
which your application connects.
Overview When your PowerBuilder application connects to an Oracle database, you can
use embedded SQL in your scripts.
If you are using these interfaces to connect to an Oracle database, you can
embed the following types of SQL statements in scripts and user-defined
functions:
• Transaction management statements
• Non-cursor statements
• Cursor statements
• Database stored procedures
When you use Oracle database interfaces, PowerBuilder supports SQL
CREATE TYPE and CREATE TABLE statements for Oracle user-defined
types (objects) in the ISQL view of the Database painter. It correctly handles
SQL SELECT, INSERT, UPDATE, and DELETE statements for user-defined
types in the Database and DataWindow painters.
Oracle Call Interface The Oracle database interfaces use the Oracle Call Interface (OCI) to interact
(OCI) with the database.
When you use embedded SQL, PowerBuilder makes the required calls to the
OCI. Therefore, you do not need to know anything about the OCI to use
embedded SQL in PowerBuilder.
See also Chapter 11, Using Oracle
Oracle SQL functions
Oracle Transaction management statements
Oracle Non-cursor statements
Oracle Cursor statements
Oracle Database stored procedures
364 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Example This example shows how to use DBHandle. Assume a successful connection
has occurred using the default transaction object (SQLCA):
// Define a variable to hold our DB handle.
long OracleHandle
// Get the handle.
OracleHandle = SQLCA.DBHandle( )
// Now that you have the LDA_DEF pointer,
// call the DLL function.
MyDLLFunction( OracleHandle, parm1, parm2, ... )
In your DLL, cast the incoming long value into a pointer to an ORA_CSA:
VOID FAR PASCAL MyDLLFunction( long lOracleHandle,
parm1_type parm1,
parm2_type parm2, ... )
{
// pLda will provide addressability to the Oracle
// logon data area
Lda_Def FAR *pLda = (Lda_Def FAR *)lOracleHandle;
// pCda will point to an Oracle cursor
Cda_Def FAR *pCda = &
GlobalAllocPtr(GMEM_MOVEABLE,sizeof(Cda_Def));
if(! pCda )
// handle error...
if(open(pCda, pLda,NULL, -1, -1, NULL, -1))
// handle error...
#ifdef Oracle7
// parse the DELETE statement
if(osql3(pCda,
"DELETE FROM EMPLOYEE WHERE Emp_ID = 100", -1);
#else
if(oparse(pCda,
"DELETE FROM EMPLOYEE
WHERE Emp_ID = 100", -1, 0, 1) :
#endif
// handle error...
if(oclose(pCda))
// handle error...
GlobalFreePtr(pCda);
}
366 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Statement Description
CONNECT Establishes the database connection. After you assign values to
the required properties of the transaction object, you can execute
a CONNECT. After the CONNECT completes successfully,
PowerBuilder automatically starts an Oracle transaction. This is
the start of a logical unit of work.
DISCONNECT Terminates a successful connection. DISCONNECT
automatically executes a COMMIT to guarantee that all changes
made to the database since the beginning of the current unit of
work are committed.
COMMIT COMMIT terminates the logical unit of work, guarantees that all
changes made to the database since the beginning of the current
unit of work become permanent, and starts a new logical unit of
work.
ROLLBACK ROLLBACK terminates a logical unit of work, undoes all
changes made to the database since the beginning of the logical
unit of work, and starts a new logical unit of work.
Note Oracle does not support the AutoCommit property of the transaction
object.
368 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This example uses the scripts for the Open and Close events in a window and
the Clicked event in a CommandButton to illustrate how you can manage
transactions in a DataWindow control. Assume the window contains a
DataWindow control dw_1 and the user enters data in dw_1 and then clicks the
Cb_Update button to send the data to the database.
Since this script uses SetTransObject to connect to the database, the
programmer is responsible for managing the transaction.
The window Open event script:
// Set the transaction object properties
// and connect to the database.
// Set the SQLCA connection properties.
SQLCA.DBMS = "O73"
SQLCA.servername = "@TNS:SHOPFLR"
SQLCA.logid = "JPL"
SQLCA.logpass = "STUMP"
// Connect to the database.
CONNECT USING SQLCA;
// Tell the DataWindow which transaction object
// to use.
dw_1.SetTransObject( SQLCA )
The CommandButton Clicked event script:
370 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Oracle SELECT
The SELECT statement contains input variables and output variables.
• Input variables are passed to the database as part of the execution and the
substitution as described above for DELETE, INSERT, AND UPDATE.
• Output variables are used to return values based on the result of the
SELECT statement.
Example 1 Assume you enter the following statement:
SELECT emp_name, emp_salary
INTO :emp_name_var, :emp_salary_var
FROM employee WHERE emp_id = :emp_id_var;
In this example, emp_id_var, emp_salary_var, and emp_name_var are
variables defined within the scope of the script that contains the SELECT
statement, and emp_id_var is processed as described in the DELETE example
above.
Both emp_name_var and emp_salary_var are output variables that will be used
to return values from the database. The data types of emp_name_var and
emp_salary_var should be the PowerScript data types that best match the
Oracle data type. When the data types do not match perfectly, PowerBuilder
converts them.
Assume the value for emp_id_var is 691 as in the previous example. When the
SELECT statement executes, the database receives the following statement:
SELECT emp_name,emp_salary
FROM employee WHERE emp_id=691;
If the statement executes with no errors, data locations for the result fields are
bound internally. The data returned into these locations is then converted as
necessary, and the appropriate PowerScript variables are set to those values.
Example 2 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. It also
assumes the data type of the emp_id column in the employee table is
CHARACTER[10].
The user enters an employee ID into the line edit sle_Emp and clicks the button
Cb_Delete to delete the employee.
The script for the Clicked event in the CommandButton Cb_Delete is:
// Make sure we have a value.
if sle_Emp.text <> "" then
// Since we have a value, let's try to delete it.
DELETE FROM employee
WHERE emp_id = :sle_Emp.text;
// Test to see if the DELETE worked.
if SQLCA.sqlcode = 0 then
// It seems to have worked, let user know.
MessageBox( "Delete",&
"The delete processed successfully!")
else
// It didn't work.
MessageBox("Error", &
"The delete failed. Invalid Employee ID")
end if
else
// No input value. Prompt user.
MessageBox( "Error", &
"An employee ID is required for delete!")
end if
372 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 3 This example assumes the default transaction object (SQLCA) has been
assigned valid values and a successful CONNECT has executed. The user
wants to extract rows from the employee table and insert them into the table
named extract_employees. The extraction occurs when the user clicks the
button Cb_Extract. The boolean variable YoungWorkers is set to TRUE or
FALSE elsewhere in the application.
The script for the Clicked event for the CommandButton Cb_Extract is:
integer EmployeeAgeLowerLimit
integer EmployeeAgeUpperLimit
// Do they have young workers?
if (YoungWorkers = TRUE ) then
// Yes - set the age limit in the YOUNG range.
// Assume no employee is under legal working age.
EmployeeAgeLowerLimit = 16
// Pick an upper limit.
EmployeeAgeUpperLimit = 42
else
// No - set the age limit in the OLDER range.
EmployeeAgeLowerLimit = 43
// Pick an upper limit that includes all
// employees.
EmployeeAgeUpperLimit = 200
end if
INSERT INTO extract_employee (emp_id,emp_name)
SELECT emp_id, emp_name FROM employee
WHERE emp_age >= :EmployeeAgeLowerLimit AND
emp_age <= :EmployeeAgeUpperLimit;
Oracle Retrieval
Retrieval using cursors is conceptually similar to retrieval in the singleton
SELECT. The main difference is that since there can be multiple rows in a
result set, you control when the next row is fetched into the PowerScript
variables.
If you expect only a single row to exist in the employee table with the specified
emp_id, use the singleton SELECT. In a singleton SELECT, you specify the
SELECT statement and destination variables in one concise SQL statement:
SELECT emp_name, emp_salary
INTO :emp_name_var, :emp_salary_var
FROM employee WHERE emp_id = :emp_id_var;
However, if the SELECT may return multiple rows, you must:
1 Declare a cursor.
2 Open it (which conceptually executes the SELECT).
374 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Note For UPDATE ... WHERE CURRENT OF cursor_name and DELETE ...
WHERE CURRENT OF cursor_name statements to execute successfully, the
SELECT statement must contain the FOR UPDATE clause.
Example Assume the SingleLineEdit sle_1 contains the state code for the retrieval:
// Declare cursor emp_curs for employee table
// retrieval.
DECLARE emp_curs CURSOR FOR
SELECT emp_id, emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
// For UPDATE WHERE CURRENT OF cursor_name and
// DELETE WHERE CURRENT OF cursor_name to work
// correctly in Oracle 7, include the FOR UPDATE
// clause in the SELECT statement.
// Declare local variables for retrieval.
string emp_id_var
string emp_name_var
// Execute the SELECT statement with
// the current value of sle_1.text.
OPEN emp_curs;
// At this point, if there are no errors,
// the cursor is available for further processing.
Fetching Rows In the singleton SELECT, you specify variables to hold the values for the
columns within the selected row. The FETCH statement syntax is similar to the
syntax of the singleton SELECT. Values are returned INTO a specified list of
variables.
This example continues the previous example by retrieving some data:
Closing the cursor The CLOSE statement terminates processing for the specified cursor. CLOSE
releases resources associated with the cursor, and subsequent references to that
cursor are allowed only if another OPEN is executed. Although you can have
multiple cursors open at the same time, you should close the cursors as soon as
possible for efficiency reasons.
Oracle Update
After a FETCH statement completes successfully, you are positioned on a
current row within the cursor. At this point, you can execute an UPDATE or
DELETE statement using the WHERE CURRENT OF cursor_name syntax to
update or delete the row. PowerBuilder enforces Oracle cursor update
restrictions, and any violation results in an execution error.
Example 1 This cursor example illustrates how you can loop through a result set. Assume
the default transaction object (SQLCA) has been assigned valid values and a
successful CONNECT has been executed.
The statements retrieve rows from the employee table and then display a
message box with the employee name in each row that is found.
// Declare the emp_curs cursor.
DECLARE emp_curs CURSOR FOR
SELECT emp_name FROM EMPLOYEE
WHERE emp_state = :sle_1.text;
// For UPDATE WHERE CURRENT OF cursor_name and
// DELETE WHERE CURRENT OF cursor_name to work
376 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Error checking
Although you should test the SQLCode after every SQL statement, these
examples show statements to test the SQLCode only to illustrate a specific
point.
Example 2 This cursor example illustrates how to use a cursor to update or delete rows.
The statements use emp_curs to retrieve rows from the employee table and
then ask whether the user wants to delete the employee:
// Declare the emp_curs cursor.
DECLARE emp_curs CURSOR FOR
SELECT emp_name FROM employee
WHERE emp_state = :sle_1.text;
// Declare a destination variable for employee
// names.
string emp_name_var
// Declare a return variable for the MessageBox.
int return_var
// Execute the SELECT statement with the current
// value of sle_1.text.
OPEN emp_curs;
// Fetch the first row from the result set.
FETCH emp_curs INTO :emp_name_var;
// Loop through result set until it is
// exhausted.
DO WHILE SQLCA.sqlcode = 0
// Ask the user to confirm the deletion.
return_var = MessageBox( "Want to delete?",&
emp_var_name, Question!, YesNo!, 2 )
// Delete?
If ( return_var = 1 ) then
// Yes - delete the employee.
DELETE FROM employee
WHERE CURRENT OF emp_curs;
End If
// Fetch the next row from the result set.
FETCH emp_curs INTO :emp_name_var;
LOOP
// All done, so close the cursor.
CLOSE emp_curs;
378 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
Procedures with a single result set You can use stored procedures that
return a single result set in DataWindow objects, reports, and embedded SQL,
but not when using the RPCFUNC keyword to declare the stored procedure as
an external function or subroutine.
Procedures with multiple result sets You can use stored procedures that
return multiple result sets only in embedded SQL. Multiple result sets are not
supported in DataWindow objects, reports, or with the RPCFUNC keyword.
The O90 database interface supports SQL CREATE TYPE and CREATE
TABLE statements for Oracle user-defined types (objects) in the ISQL view of
the Database painter. It correctly handles SQL SELECT, INSERT, UPDATE,
and DELETE statements for user-defined types in the Database and
DataWindow painters. For more information, see Chapter 11, Using Oracle.
Methods for using There are three methods for using Oracle stored procedures in a PowerBuilder
Oracle stored application:
procedures
• As a data source for DataWindow objects.
• RPCFUNC keyword (Recommended) Use the RPCFUNC keyword to
declare the stored procedure as an external function or external subroutine.
You cannot use the RPCFUNC keyword with Oracle stored procedures
that return result sets. Using the RPCFUNC keyword to declare the stored
procedure provides the best performance and has more supported features
and fewer limitations than the DECLARE Procedure and PBDBMS
methods.
• DECLARE Procedure statement Use the DECLARE Procedure
(Oracle DECLARE and EXECUTE) statement to declare the stored
procedure as an external function or external subroutine. This includes
support for fetching against Oracle stored procedures that return result
sets.
See also Supported features when using Oracle stored procedures
Using DECLARE, EXECUTE, FETCH, and CLOSE with Oracle stored
procedures
Supported features The following are supported and unsupported Oracle PL/SQL features when
with DECLARE you use the DECLARE Procedure statement:
Procedure statement
You can You cannot
Use IN and OUT parameters Use IN OUT parameters
Use up to 256 parameters Pass and return records
Use more than 256 parameters
Pass and return PowerScript arrays
(PL/SQL tables)
Overload procedures
For an example that uses a REF CURSOR variable of type IN OUT, see
Chapter 11, Using Oracle.
380 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
382 PowerBuilder
CHAPTER 23 Using Embedded SQL with Oracle
EXECUTE proc_update;
if SQLCA.SqlCode 0 then
SQLCA.f_out_error()
RETURN -1
end if
FETCH proc_update INTO :o_id_object, o_message;
if SQLCA.SqlCode 0 then
SQLCA.f_out_error()
RETURN -1
end if
Oracle FETCH
To access rows returned by a procedure, you use the FETCH statement as you
did for cursors. You can execute the FETCH statement after any EXECUTE
statement that executes a procedure that has output parameters.
Example FETCH dept_proc INTO :name_var;
The FETCH FROM procedure statements must exactly match the output
parameters returned by the stored procedure when it executes.
Oracle CLOSE
If a database stored procedure has output parameters, it must be closed when
processing is complete.
Closing a procedure looks the same as closing a cursor.
Example CLOSE dept_proc;
384 PowerBuilder
PA RT 7 Appendix
385
APPENDIX Adding Functions to the PBODB170 Initialization File
About this appendix Usually, you do not need to modify the PBODB170 initialization file. In certain
situations, however, you might need to add functions to the PBODB170
initialization file for connections to your back-end DBMS through the ODBC
or OLE DB interface in PowerBuilder.
This appendix describes how to add functions to the PBODB170 initialization
file if necessary.
Contents
Topic Page
About the PBODB170 initialization file 387
Adding functions to PBODB170.INI 388
388 PowerBuilder
APPENDIX Adding Functions to the PBODB170 Initialization File
PBDefaultExpressions='YES'
DelimitIdentifier='YES'
PBDateTimeInvalidInSearch='NO'
PBTimeInvalidInSearch='YES'
PBQualifierIsOwner='NO'
PBSpecialDataTypes='WATCOM_SPECIALDATATYPES'
IdentifierQuoteChar='"'
PBSystemOwner='sys,dbo'
PBUseProcOwner='YES'
SQLSrvrTSName='YES'
SQLSrvrTSQuote='YES'
SQLSrvrTSDelimit='YES'
ForeignKeyDeleteRule='Disallow if Dependent Rows
Exist (RESTRICT),Delete any Dependent Rows
(CASCADE),Set Dependent Columns to NULL
(SET NULL)'
TableListType=’GLOBAL TEMPORARY’
3 Find the name of the section in PBODB170.INI that contains function
information for your back-end DBMS.
To find this section, look for a line similar to the following in the DBMS
Driver/DBMS Settings entry:
PBFunctions='section_name'
For example, the following line in the DBMS Driver/DBMS Settings entry
for SQL Anywhere indicates that the name of the Functions section is
ASA_FUNCTIONS:
PBFunctions='ASA_FUNCTIONS'
4 Find the Functions section for your back-end DBMS in PBODB170.INI.
For example, here is the Functions section for SQL Anywhere:
;*********************************************
;Functions
;*********************************************
[ASA_FUNCTIONS]
AggrFuncs=avg(x),avg(distinct x),count(x),
count(distinct x),count(*),list(x),
list(distinct x),max(x),max(distinct x),
min(x),min(distinct x),sum(x),sum(distinct x)
Functions=abs(x),acos(x),asin(x),atan(x),
atan2(x,y),ceiling(x),cos(x),cot(x),degrees(x),
exp(x),floor(x),log(x),log10(x),
mod(dividend,divisor),pi(*),power(x,y),
radians(x),rand(),rand(x),
remainder(dividend,divisor),round(x,y),
sign(x),sin(x),sqrt(x),tan(x),
"truncate"(x,y),ascii(x),byte_length(x),
byte_substr(x,y,z),char(x),char_length(x),
charindex(x,y),difference(x,y)insertstr(x,y,z),
lcase(x),left(x,y),length(x), locate(x,y,z),
lower(x),ltrim(x),patindex('x',y),repeat(x,y),
replicate(x,y),right(x,y),rtrim(x),
similar(x,y),soundex(x),space(x),str(x,y,z),
string(x,...),stuff(w,x,y,z),substr(x,y,z),
trim(x),ucase(x),upper(x),date(x),
dateformat(x,y),datename(x,y),day(x),
dayname(x),days(x),dow(x),hour(x),hours(x),
minute(x),minutes(x),minutes(x,y),month(x),
monthname(x),months(x),months(x,y),now(*),
quarter(x),second(x),seconds(x),seconds(x,y),
today(*),weeks(x),weeks(x,y),year(x),years(x),
years(x,y),ymd(x,y,z),dateadd(x,y,z),
datediff(x,y,z),datename(x,y),datepart(x,y),
getdate(),cast(x as y),convert(x,y,z),
hextoint(x),inttohex(x),
connection_property(x,...),datalength(x),
db_id(x),db_name(x),db_property(x),
next_connection(x),next_database(x),
property(x),property_name(x),
property_number(x),property_description(x),
argn(x,y,...),coalesce(x,...),
estimate(x,y,z),estimate_source(x,y,z),
experience_estimate(x,y,z),ifnull(x,y,z),
index_estimate(x,y,z),isnull(x,...),
number(*),plan(x),traceback(*)
5 To add a new function, type a comma followed by the function name at the
end of the appropriate function list, as follows:
• Aggregate functions Add aggregate functions to the end of the
AggrFuncs list.
• All other functions Add all other functions to the end of the
Functions list.
Case sensitivity
If the back-end DBMS you are using is case sensitive, be sure to use the
required case when you add the function name.
390 PowerBuilder
APPENDIX Adding Functions to the PBODB170 Initialization File
The following example shows a new function for SQL Anywhere added at
the end of the Functions list:
;*********************************************
;Functions
;*********************************************
[ASA_FUNCTIONS]
AggrFuncs=avg(x),avg(distinct x),count(x),
count(distinct x),count(*),list(x),
list(distinct x),max(x),max(distinct x),
min(x),min(distinct x),sum(x),sum(distinct x)
Functions=abs(x),acos(x),asin(x),atan(x),
atan2(x,y),ceiling(x),cos(x),cot(x),degrees(x),
exp(x),floor(x),log(x),log10(x),
mod(dividend,divisor),pi(*),power(x,y),
radians(x),rand(),rand(x),
...
number(*),plan(x),traceback(*),newfunction()
6 Save your changes to PBODB170.INI.
392 PowerBuilder
APPENDIX Adding Functions to the PBODB170 Initialization File
• All other functions Add all other functions to the end of the
Functions list.
Case sensitivity
If the back-end DBMS you are using is case sensitive, be sure to use the
required case when you add the function name.
The following example shows (in bold) a new DB2/2 function named
substr() added at the end of the Functions list:
;***********************************************
;Functions
;***********************************************
[DB22_FUNCTIONS]
AggrFuncs=avg(),count(),list(),max(),min(),sum()
Functions=curdate(),curtime(),hour(), substr()
5 Save your changes to PBODB170.INI.
394 PowerBuilder
Index
A B
accessing databases basic procedures
ODBC data sources 25 defining database interfaces 80
troubleshooting any connection 204 editing database profiles 172
troubleshooting JDBC connections 227 importing and exporting database profiles 177
troubleshooting ODBC connections 219 preparing ODBC data sources 24
Adaptive Server Enterprise database interface 287 selecting a database profile to connect 169
Adaptive Server Enterprise database interface, using setting database parameters 185
embedded SQL 287 setting database preferences 190
ADO.NET interface setting DBParm parameters 187
components 55 sharing database profiles 173
getting help 53 starting JDBC Driver Manager Trace 230
getting identity column values 61 starting ODBC Driver Manager Trace 221
installing data providers 59 stopping Database Trace 212
specifying connection parameters 60 stopping JDBC Driver Manager Trace 232
using Data Link 60 stopping ODBC Driver Manager Trace 224
API conformance levels for ODBC 22
applications
connecting to databases from 195
in database interface connections 78 C
in ODBC connections 17 case sensitivity, in PBODB initialization file 390, 393
setting AutoCommit and Lock 198 client software
setting database preferences 195 DirectConnect 159
setting DBParm parameters 188, 190 Informix 101, 109
tracing any database connection from 209 Microsoft SQL Server 117
tracing JDBC connections from 230 Oracle 138
tracing ODBC connections from 221 SAP Adpative Server Enterprise 86
using Preview tab to set connection options 9, CLOSE Cursor 303, 329, 352
172, 187, 188, 196 CLOSE Procedure 257, 281, 308, 332, 357
using Preview tab to set trace options 209, 222, columns
230 identity, SAP Adaptive Server Enterprise 82
ASE DBMS identifier 81 in extended attribute system tables 181
AutoCommit database preference special timestamp, in Sybase SQL Anywhere 34
displayed on Preview tab 196 SQL naming conventions 24
setting in database profile 192 COMMIT 241, 268, 290, 316, 340, 366
setting in PowerBuilder script 195 conformance levels for ODBC drivers 21
AutoCommit Transaction object property 197 CONNECT 241, 268, 290, 316, 340, 366
Connect DB at Startup database preference 194
connect descriptors
396 PowerBuilder
Index
398 PowerBuilder
Index
G initialization files
DBMS_PROFILES section 176
General page in Database Preferences dialog box 194
in ODBC connections 25
General property page in Database Preferences
locating when sharing database profiles 173
property sheet 174
ODBC 26
Generate Trace check box in Database Profile Setup
ODBCINST 26
dialog box 212
PBODB adding functions to 387
granting permissions on extended attribute system
reading DBMS value from 211, 213
tables 183
reading DBParm values from 190, 224, 226, 231,
233
storing connection parameters 11, 171
H suppressing password display 171
INSERT statement 245, 272, 296, 321, 345, 370
help 23 installing
Database Trace, using 204 Java virtual machines 39
for ODBC drivers 23, 28 interval datatype, Informix 103
JDBC Driver Manager Trace, using 228 IQ
JDBC Web site 37, 53 using JDBC interface 40
Microsoft Universal Data Access 45, 53 using ODBC interface 16
ODBC Driver Manager Trace, using 219 isolation levels and lock values, setting in database
online Help, using 15, 23 profiles 192
Sybase Web site 45 ISQL, using to install stored procedures 99
heterogeneous cross-database joins 95
J
I Java virtual machines, installing 39
I10 DBMS identifier 101 Java Web site 37
IBM database interface, DB2SYSPB.SQL script, using JDBC connections, troubleshooting 227
162 JDBC database interface, troubleshooting 227
identity columns and datatype, SAP Adaptive Server JDBC Driver Manager Trace
Enterprise 82 about 227
identity columns, ADO.NET 61 availability on different platforms 228
importing a database profile 177 performance considerations 228
IN9 DBMS identifier 101 specifying a nondefault log file 229
Informix client software 101, 109 starting in database profiles 228
Informix database interface 315 starting in PowerBuilder scripts 230
client software required 109 stopping in database profiles 232
connection components 108 stopping in PowerBuilder scripts 233
databases supported 101 syntax displayed on Preview tab 230
datatypes supported 101 viewing the log 234
features supported by I10 103 JDBC drivers, troubleshooting 227
installing 110 JDBC interface
preparing the database 109 about 37
verifying the connection 110 components 38
Informix database interface, using embedded SQL data types supported 41
315
L N
large datatypes, and SQL Server 115
naming conventions, tables and columns 24
large object, as output parameter in Oracle stored procedure
NewLogic, database profile setting 11
147
non-cursor statements 244, 272, 295, 320, 345, 370
Level 1 API conformance level for ODBC 22
Lock database preference
displayed on Preview tab 196
setting in database profiles 192 O
setting in PowerBuilder script 195
O10 DBMS identifier 133
Lock Transaction object property 197
O10 Oracle 10g Driver 133
lock values and isolation levels, setting in database profiles
O90 DBMS identifier 133
192
O90 Oracle 9i Driver 133
LOG files
ODBC 23
JDBC.LOG 227, 234
ODBC (Open Database Connectivity)
PBTRACE.LOG 204, 214
about 15
specifying nondefault for JDBC Driver Manager Trace
components 17
229
defining data sources 25
SQL.LOG 219, 226
defining multiple data sources 28
logging in to databases for the first time 178
driver conformance levels 22
ODBC initialization file 26
ODBCINST initialization file 26
preparing data sources 24
400 PowerBuilder
Index
translators, selecting for drivers 29 adding to new section in PBODB initialization file
ODBC connect strings 27 391
ODBC data sources ODBC initialization file
accessing 25 about 26
creating configurations and database profiles 25 and PBODB initialization file 391
defining 25 ODBC interface
defining multiple 28 about 15
editing database profiles 172 connecting to data sources 169
in ODBC connections 17 DLL files required 17
in ODBC initialization file 26 initialization files required 25
in ODBCINST initialization file 26 ODBC initialization file 26
PBODB initialization file 387 PBODB initialization file 387
preparing 24 troubleshooting 204, 219
sharing database profiles 173 using 16
Sybase SQL Anywhere 30 ODBCINST initialization file 26
translators, selecting for drivers 29 OLE DB interface 46
troubleshooting 204, 219 components 48
ODBC database interface 237 data provider 46
ODBC database interface, using embedded SQL 237 getting help 45
ODBC Driver Manager 17 installing data providers 50, 51
ODBC Driver Manager Trace object interfaces supported 46
about 219 obtaining data providers, from other vendors 49
performance considerations 219 PBOLE<version>.DLL 49
sample output 227 specifying connection parameters 51
starting in database profiles 220 using Data Link 52
starting in PowerBuilder scripts 221 OLEDB database interface 263
stopping in database profiles 224 OLEDB database interface, using embedded SQL 263
stopping in PowerBuilder scripts 225 Open Client software, Sybase 50, 59, 86, 159
syntax displayed on Preview tab 222 ORA DBMS identifier 133
viewing the log 226 ORA Oracle 11g Driver 133
ODBC drivers Oracle database interface 363
about 16 Oracle database interface, using embedded SQL 363
API conformance levels 22 Oracle database interfaces
conformance levels, recommendations for 21 client software required 138
displaying Help 15, 23, 28 connect strings or descriptors, specifying 142
in ODBC connections 17 connection components 136
multiple-tier 20 datatypes supported 134
PBODB initialization file 387 defining 142
SQL conformance levels 22 preparing the database 138
Sybase SQL Anywhere 30 using Oracle stored procedures 143
translators, selecting 29 verifying the connection 139
troubleshooting 204, 219 versions supported 133
using 16 Oracle SQL*Net client software 138
ODBC functions Oracle stored procedure
adding to existing section in PBODB initialization RPC calls to 148
file 388 using LOB output parameter 147
402 PowerBuilder
Index
ODBC initialization file 26 Select Tables dialog box, Show system tables check box
ODBCINST initialization file 26 179
result sets, using Oracle stored procedures 144 Select Translator dialog box 29
ROLLBACK 241, 268, 290, 316, 340, 366 semicolons, as default SQL terminator character 144
RPCFUNC keyword 143 SERVER directory files
for creating repository in DB2 databases 163
for installing stored procedures in Adaptive Server
Enterprise databases 96
S server name, specifying for Sybase Open Client
SAP Adaptive Server Anywhere. See SAP SQL directory services 93
Anywhere shared database profiles
SAP Adaptive Server Enterprise database interface maintaining 176
287 saving in local initialization file 175
client software required 50, 59, 86 setting up 174
creating a DW based on a heterogeneous cross- Show system tables check box 179
database join 95 SNC DBMS identifier 113
datatypes supported 82 sp_pb<version>table stored procedure
defining 88 in PBSYC.SQL script 97
directory services, using 91 in PBSYC2.SQL script 98
identity columns 82 SQL Anywhere ODBC Configuration dialog box 33
installing 87 SQL conformance levels for ODBC 22
installing stored procedures 95 SQL files
platforms supported 81 DB2SYSPB.SQL 163
preparing the database 49, 58, 86 PBSYC.SQL 96
security services, using 89 PBSYC2.SQL 98
verifying the connection 88 SQL naming conventions for tables and columns 24
versions supported 81 SQL terminator character, changing in Database painter
SAP Adaptive Server Enterprise database interface, 144, 194
using embedded SQL 287 SQL_OPT_TRACE parameter in ConnectOption
scope_identity, using in ADO.NET 61 DBParm
scripts, PowerBuilder adding to PowerBuilder application script 223
datatype conversions 84 changing to SQL_OPT_TRACE_OFF in
setting database preferences 195 PowerBuilder application script 225
setting DBParm values 188 SQL_OPT_TRACEFILE parameter in ConnectOption
starting Database Trace 209 DBParm
starting JDBC Driver Manager Trace 230 adding to PowerBuilder application script 223
starting ODBC Driver Manager Trace 221 SQL.LOG file
using Preview tab to set connection options 9, about 219
172, 187, 188, 196 leaving open 226
using Preview tab to set trace options 209, 222, performance considerations 219
230 sample output 227
using ProfileString function to read 190, 198 viewing 226
security services, Sybase Open Client. See Sybase SQL*Net client software, Oracle 138
Open Client security services SQLCA Transaction object
SELECT 245, 273, 321, 346, 371 setting AutoCommit property 197
setting ConnectOption DBParm 223
404 PowerBuilder
Index
U
Unicode
406 PowerBuilder