AWS Certified Solutions Architect Associate Blueprint
AWS Certified Solutions Architect Associate Blueprint
Tutorial
Simply Easy Learning
About the tutorial
DB2 Tutorial
This tutorial provides you the basic understanding of concepts of database, database
installation and management. At the end of the tutorial you should be equipped with
well understanding of database management concepts.
Audience
This tutorial is designed for the readers pursuing education in database management
domain and all enthusiastic readers.
Prerequisites
This tutorial is designed and developed for absolute beginners. Though, awareness
about software systems, operating systems and computer fundamentals would be
beneficial.
All the content and graphics published in this e-book are the property of Tutotorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent of
the publisher.
You strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd.
provides no guarantee regarding the accuracy, timeliness or completeness of our website or
its contents including this tutorial. If you discover any errors on our website or in this tutorial,
please notify us at contact@tutorialspoint.com
DB2 Tutorial
Table of Contents
INTRODUCTION TO DB2 .....................................................................................................................1
OVERVIEW ................................................................................................................................................... 1
HISTORY....................................................................................................................................................... 1
VERSIONS ..................................................................................................................................................... 1
DATA SERVER EDITIONS AND FEATURES.............................................................................................................. 2
DB2 SERVER INSTALLATION ................................................................................................................4
INTRODUCTION ............................................................................................................................................. 4
HARDWARE REQUIREMENTS ............................................................................................................................ 4
SOFTWARE REQUIREMENTS ............................................................................................................................. 4
CHECKING SYSTEM COMPATIBILITY.................................................................................................................... 4
INSTALLING DB2 ON LINUX OPERATING SYSTEM ................................................................................................. 4
VERIFYING DB2 INSTALLATION....................................................................................................................... 11
COMMAND LINE PROCESSOR (CLP)................................................................................................................ 13
ACCESSING DB2 .......................................................................................................................................... 13
DB2 INSTANCE ................................................................................................................................. 14
INTRODUCTION ........................................................................................................................................... 14
ARCHITECTURE OF INSTANCE IN DB2 PRODUCT ................................................................................................ 15
MULTIPLE INSTANCES ................................................................................................................................... 15
Creating instance on Linux .................................................................................................................. 15
LISTING INSTANCES ...................................................................................................................................... 15
INSTANCE ENVIRONMENT COMMANDS ............................................................................................................ 16
db2stop ............................................................................................................................................... 17
CREATING AN INSTANCE ................................................................................................................................ 17
ARRANGING COMMUNICATION PORT AND HOST FOR AN INSTANCE ...................................................................... 18
UPDATING AN INSTANCE ............................................................................................................................... 19
UPGRADING AN INSTANCE ............................................................................................................................. 19
db2iupgrade ........................................................................................................................................ 20
DROPPING AN INSTANCE ............................................................................................................................... 20
db2idrop .............................................................................................................................................. 20
USING OTHER COMMANDS WITH INSTANCE ...................................................................................................... 20
DATABASES ..................................................................................................................................... 22
DATABASE ARCHITECTURE ............................................................................................................................. 22
DATABASE DIRECTORY .................................................................................................................................. 23
PARTITIONED GLOBAL DIRECTORY ................................................................................................................... 23
MEMBER SPECIFIC DIRECTORY........................................................................................................................ 23
CREATING DATABASE .................................................................................................................................... 24
CREATING NON-RESTRICTIVE DATABASE ........................................................................................................... 24
CREATING RESTRICTIVE DATABASE .................................................................................................................. 24
CREATING DATABASE WITH DIFFERENT USER DEFINED LOCATION .......................................................................... 25
VIEWING LOCAL OR SYSTEM DATABASE DIRECTORY FILES..................................................................................... 25
ACTIVATING DATABASE ................................................................................................................................. 26
DEACTIVATING DATABASE ............................................................................................................................. 26
CONNECTING TO DATABASE ........................................................................................................................... 26
VERIFYING IF DATABASE IS RESTRICTIVE............................................................................................................ 27
i
DB2 Tutorial
ii
DB2 Tutorial
iii
DB2 Tutorial
iv
DB2 Tutorial
Introduction to DB2
1
This chapter describes history of DB2, its versions, editions and their respective
features.
Overview
DB2 is a database product from IBM. It is a Relational Database Management System
(RDBMS). DB2 is designed to store, analyze and retrieve the data efficiently. DB2
product is extended with the support of Object-Oriented features and non-relational
structures with XML.
History
Initially, IBM had developed DB2 product for their specific platform. Since year 1990,
it decided to develop a Universal Database (UDB) DB2 Server, which can run on any
authoritative operating systems such as Linux, UNIX, and Windows.
Versions
For IBM DB2, the UDB current version is 10.5 with the features of BLU Acceleration
and its code name as 'Kepler'. All the versions of DB2 till today are listed below:
3.4 Cobweb
8.1, 8.2 Stinger
9.1 Viper
9.5 Viper 2
9.7 Cobra
9.8 It added features with Only PureScale
10.1 Galileo
10.5 Kepler
1
DB2 Tutorial
Editions Features
Connection concentrator
Pure XML
Backup compression
Homogeneous Federations
Online Reorganization
Pure XML
Backup compression
Express Edition It is designed for entry level and mid-size business organizations.
2
DB2 Tutorial
Backup compression
3
DB2 Tutorial
Introduction
You can download the DB2 Server trial version or purchase the product license from
www.ibm.com. There are two separate DB2 servers available for downloading,
depending upon the size of operating system, on which it is intended to execute. For
example, if you want to download a DB2 server for 32bit Linux or UNIX operating
system, then you need to download a 32 bit DB2 server. The same applies for 64bit
DB2 server.
Hardware requirements
Processor : Minimum Core 2Duo
Software requirements
Before installing the DB2 server, your system needs to get ready with the required
software on it. For Linux, you need to install libstdc++6.0.
4
DB2 Tutorial
Figure-1Compatibility
Requirements of Linux
Follow the given steps for installing DB2 on your Linux system:
5
DB2 Tutorial
Click Next.
[Figure-3]
Figure-3 Setup of DB2 AESE - DB2 Setup
Wizard Welcome Screen
Click Next.
[Figure-4]
6
DB2 Tutorial
Click Next.
[Figure-5]
Click Next.
[Figure-6]
7
DB2 Tutorial
[Figure-7]
Click Next.
8
DB2 Tutorial
[Figure-9]
[Figure-10]
9
DB2 Tutorial
Click Next.
Click Next.
10
DB2 Tutorial
Click Next.
[Figure-13]
Click Finish.
[Figure 14]
db2level
This command shows the current version and service level of the installed DB2 product
for current instance.
Syntax:
11
DB2 Tutorial
db2level
Example:
db2level
Output:
db2licm
This command shows all the license related information of our DB2 Product.
Syntax:
db2licm <parameter>
Example:
db2licm -l
Output:
12
DB2 Tutorial
1. Command mode: In this mode, each command and SQL statement must be
prefixed by db2. For example, query db2 activate database sample.
2. Interactive input mode: you can launch this mode by using the db2 command.
Here, you can pass SQL statements without prefix. For example, activate
database sample.
3. Batch mode: Here, you need to create a script file, which contains all SQL queries
of requirements and save the file with .db2 extension. You can call this in
command line using syntax db2 tf <filename.db2>.
Note: All the Commands and statements are explained in CLP command [First
mode] only.
Accessing DB2
13
DB2 Tutorial
DB2 Instance
3
Introduction
An Instance is a logical environment for DB2 Database Manager. Using instance, you
can manage databases. Depending on our requirements, you can create multiple
instances on one physical machine. The contents of Instance directory are:
Node Directory
For DB2 Database Server, the default instance is DB2. It is not possible to change
the location of Instance directory after its creation. An instance can manage multiple
databases. In an instance, each database has a unique name, its own set of catalog
tables, configurations files, authorities and privileges.
14
DB2 Tutorial
Multiple instances
You can create multiple instances in one DB2Server on Linux, UNIX and Windows. It is
possible to install multiple DB2Servers on a physical machine.
An Instance folder contains database configuration files and folders. The Instance
directory is stored at different locations on Windows depending on the operating
system versions.
Listing instances
The following command is used to list instances:
db2ilist
This command lists all the instances that are available on a system.
Syntax:
15
DB2 Tutorial
db2ilist
Example: [To see how many instances are created in DB2 copy]
db2ilist
Output:
db2inst1
db2inst2
db2inst3
Get instance
This command shows details of the currently running instance.
Syntax:
db2 get instance
Example: [To see the current instance which activated the current user]
Output:
Set instance
To start or stop the database manager of an instance on DB2 UDB, the following
command is executed for the current instance. Syntax:
set db2instance=<instance_name>
set db2instance=db2inst1
db2start
16
DB2 Tutorial
Using this command, you can start an instance. Before this, you need to run set
instance.
Syntax:
db2start
db2start
Output:
db2stop
Using this command you can stop a running instance.
Syntax:
db2stop
Output:
Creating an instance
Let us see how to create a new instance.
db2icrt
If you want to create a new instance, you need to log in with root. Instance id is not a
root id or a root name.
Syntax:
Example: [To create a user for instance with name db2inst2 in group
db2iadm1 and password db2inst2]
17
DB2 Tutorial
Step2: Go to the DB2 instance directory in root user for create new instance.
Location:
cd /opt/ibm/db2/v10.1/instance
Syntax:
Example: [To create a new instance db2inst2 in user db2inst2 with the
features of ESE (Enterprise Server Edition)]
Output:
Syntax:
Example: [Adding 50001/tcp port number for instance db2inst2 with variable
db2c_db2inst2 in services file]
db2c_db2inst2 50001/tcp
18
DB2 Tutorial
Output:
Syntax 2: set the tcpip communication protocol for the current instance
db2set DB2COMM=tcpip
Syntax 3: [Stopping and starting current instance to get updated values from
database manager configuration]
db2stop
db2start
Updating an instance
You can update an instance using following command:
db2iupdt
This command is used to update the instance within the same version release. Before
executing this command, you need to stop the instance database manager using
db2stop command. The syntax below inst_name indicates the previous released or
installed db2 server instance name, which you want to update to newer release or
installed db2 server version.
db2iupdt <inst_name>
Example1:
./db2iupdt db2inst2
db2iupdt -D <inst_name>
Example2:
db2iupdt -D db2inst2
Upgrading an instance
You can upgrade an instance from previous version of DB2 copy to current newly
installed version of DB2 copy.
19
DB2 Tutorial
db2iupgrade
On Linux or UNIX system, this command is located in DB2DIR/instance directory. In
the following syntaxes, inst_name indicates the previous version DB2 instance and
inst_username indicates the current installed version DB2 copy instance user.
Syntax:
Example:
Command Parameters:
-k : Keeps the pre-upgrade instance type if it is supported in the DB2 copy, from
where you are running this command.
If you are using the Super User (su) on Linux for db2iupgrade command, you
must issue the su command with the - option.
Dropping an instance
You can drop or delete the instance, which was created by db2icrt command.
db2idrop
On Linux and UNIX operating system, this command is located in the
DB2_installation_folder/instance directory.
Output:
20
DB2 Tutorial
Syntax 2: [To see the current instance with operating bits and release version]
Example:
Output:
Example:
Output:
INST_NAME --------------------------------------
db2inst1
1 record(s) selected.
db2set db2instdef=<inst_name> -g
db2set db2instdef=db2inst2 -g
21
DB2 Tutorial
Databases
4
This chapter describes creating, activating and deactivating the databases with the
associated syntax.
Database architecture
22
DB2 Tutorial
Database directory
Database directory is an organized repository of databases. When you create a
database, all the details about database are stored in a database directory, such as
details of default storage devices, configuration files, and temporary tables list etc.
Partition global directory is created in the instance folder. This directory contains all
global information related to the database. This partition global directory is named as
NODExxxx/SQLyyy, where xxxx is the data partition number and yyy is the database
token.
23
DB2 Tutorial
Deadlocks event monitor file. The detailed deadlock events monitor files are
stored in the database directory of the catalog node in case of ESE and
partitioned database environment.
Creating database
You can create a database in instance using the CREATE DATABASE command. All
databases are created with the default storage group IBMSTOGROUP, which is
created at the time of creating an instance. In DB2, all the database tables are stored
in tablespace, which use their respective storage groups.
The privileges for database are automatically set as PUBLIC [CREATETAB, BINDADD,
CONNECT, IMPLICIT_SCHEMA, and SELECT], however, if the RESTRICTIVE option is
present, the privileges are not granted as PUBLIC.
Output:
Syntax: [In the syntax below, db_name indicates the database name.]
Example: [To create a new restrictive database with the name two]
24
DB2 Tutorial
Syntax: [In the syntax below, db_name indicates the database name and
data_location indicates where have to store data in folders and
db_path_location indicates driver location of data_location.]
db2 create database '<db_name>' on '<data location>'
dbpath on '<db_path_location>'
Example: [To create database named four, where data is stored in data1 and
this folder is stored in dbpath1]
db2 create database four on '/data1' dbpath on '/dbpath1'
Syntax:
Example:
Output:
Database 1 entry:
Database 2 entry:
25
DB2 Tutorial
Activating database
This command starts up all necessary services for a particular database so that the
database is available for application.
Deactivating database
Using this command, you can stop the database services.
Syntax:
db2 deactivate db <db_name>
Connecting to database
After creating a database, to put it into use, you need to connect or start database.
Syntax:
Output:
26
DB2 Tutorial
Output:
Restrict access = NO
27
DB2 Tutorial
Output:
28
DB2 Tutorial
Return Status = 0
Index Space
XML data
System files
Example: [To Connect one Database with the user id db2inst4 and password
db2inst4]
Output:
Database Connection Information
Database server = DB2/LINUXX8664 10.1.0
SQL authorization ID = DB2INST4
Local database alias = ONE
29
DB2 Tutorial
Syntax: [The syntax below shows the result of authority services for current
database]
Example:
Output:
AUTHORITY D_USER D_GROUP D_PUBLIC ROLE_USER ROLE_GROUP ROLE_PUBLIC D_ROLE
ACCESSCTRL * * N * * N *
BINDADD * * Y * * N *
CONNECT * * Y * * N *
CREATETAB * * Y * * N *
CREATE_EXTERNAL_ROUTINE * * N * * N *
CREATE_NOT_FENCED_ROUTINE * * N * * N *
CREATE_SECURE_OBJECT * * N * * N *
DATAACCESS * * N * * N *
DBADM * * N * * N *
EXPLAIN * * N * * N *
IMPLICIT_SCHEMA * * Y * * N *
LOAD * * N * * N *
QUIESCE_CONNECT * * N * * N *
SECADM * * N * * N *
SQLADM * * N * * N *
SYSADM * * * * * * *
SYSCTRL * * * * * * *
SYSMAINT * * * * * * *
SYSMON * * * * * * *
WLMADM * * N * * N *
20 record(s) selected.
30
DB2 Tutorial
Dropping Database
Using the Drop command, you can remove our database from instance database
directory. This command can delete all its objects, table, spaces, containers and
associated files.
Output:
31
DB2 Tutorial
Bufferpools
5
This chapter introduces you to Bufferpools in the database.
Introduction
The bufferpool is portion of a main memory space which is allocated by the database
manager. The purpose of bufferpools is to cache table and index data from disk. All
databases have their own bufferpools. A default bufferpool is created at the time of
creation of new database. It called as IBMDEFAULTBP. Depending on the user
requirements, it is possible to create a number of bufferpools. In the bufferpool, the
database manager places the table row data as a page. This page stays in the
bufferpool until the database is shutdown or until the space is written with new data.
The pages in the bufferpool, which are updated with data but are not written onto the
32
DB2 Tutorial
disk, are called Dirty pages. After the updated data pages in the bufferpool are
written on the disk, the bufferpool is ready to take another data.
Bufferpool sizes
The size of the bufferpool page is set when you use the CREATE DATABASE
command. If you do not specify the page size, it will take default page size, which is
4KB. Once the bufferpool is created, it is not possible to modify the page size later.
Output:
IBMDEFAULTBP
1 -
-2 4096 N 0 0 -
1 record(s) selected.
Syntax: [In the syntax below,bp_name indicates bufferpool name and size
indicates size for page you need to declare for bufferpools (4K,8K,16K,32K)]
33
DB2 Tutorial
Example: [To create a new bufferpool with name bpnew and size
8192(8Kb).]
Output:
Output:
34
DB2 Tutorial
Tablespaces
6
This chapter describes the tablespaces in detail.
Introduction
A table space is a storage structure, it contains tables, indexes, large objects, and long data. It can be used
to organize data in a database into logical storage group which is related with where data stored on a
system. This tablespaces are stored in database partition groups.
Recoverability: Tablespaces make backup and restore operations more convenient. Using a single
command, you can make backup or restore all the database objects in tablespaces.
35
DB2 Tutorial
Automatic storage Management: Database manager creates and extends containers depending on the
needs.
Memory utilization: A single bufferpool can manage multiple tablespaces. You can assign temporary
tablespaces to their own bufferpool to increase the performance of activities such as sorts or joins.
Container
Tablespaces contains one or more containers. A container can be a directory name, a device name, or a
filename. In a database, a single tablespace can have several containers on the same physical storage
device. If the tablespace is created with automatic storage tablespace option, the creation and
management of containers is handled automatically by the database manager. If it is not created with
automatic storage tablespace option, you need to define and manage the containers yourself.
Default tablespaces
When you create a new database, the database manager creates some default tablespaces for database.
These tablespace is used as a storage for user and temporary data. Each database must contain at least
three tablespaces as given here:
1. Catalog tablespace
2. User tablespace
3. Temporary tablespace
Catalog tablespace: It contains system catalog tables for the database. It is named as SYSCATSPACE and it
cannot be dropped.
User tablespace: This tablespace contains user-defined tables. In a database, we have one default user
tablespace, named as USERSPACE1. If you do not specify user-defined tablespace for a table at the time
you create it, then the database manager chooses default user tablespace for you.
Temporary tablespace: A temporary tablespace contains temporary table data. This tablespace contains
system temporary tablespaces or user temporary tablespace.
System temporary tablespace holds temporary data required by the database manager while performing
operation such as sorts or joins. A database must have at least one system temporary tablespace and it is
named as TEMPSPACE1. It is created at the time of creating the database. User temporary tablespace
holds temporary data from tables. It is created with DECLARE GLOBAL TEMPORARY TABLE or CREATE
GLOBAL TEMPORARY TABLE statement. This temporary tablespace is not created by default at the time of
database creation.
Tablespaces can be setup in different ways, depending on how you want to use them. You can setup the
operating system to manage tablespace allocation, you can let the database manager allocate space or
you can choose automatic allocation of tablespace for your data.
System Managed Space (SMS): The operating systems file system manager allocates and manages the
space where the table is stored. Storage space is allocated on demand. This model consists of files
36
DB2 Tutorial
representing database objects. This tablespace type has been deprecated in Version 10.1 for user-defined
tablespaces, and it is not deprecated for catalog and temporary tablespaces.
Database Managed Space (DMS): The Database Server controls the storage space. Storage space is pre-
allocated on the file system based on container definition that you specify when you create the DMS table
space. It is deprecated from version 10.1 fix pack 1 for user-defined tablespaces, but it is not deprecated
for system tablespace and temporary tablespace.
Automatic Storage Tablespace: Database server can be managed automatically. Database server creates
and extends containers depend on data on database. With automatic storage management, it is not
required to provide container definitions. The database server looks after creating and extending
containers to make use of the storage allocated to the database. If you add storage space to a storage
group, new containers are automatically created when the existing container reach their maximum
capacity. If you want to use the newly-added storage immediately, you can rebalance the tablespace.
Temporary DMS and automatic storage tablespaces, the page size you choose for your database
determines the maximum limit for the tablespace size. For table SMS and temporary automatic storage
tablespaces, the page size constrains the size of table itself. The page sizes can be 4kb, 8kb, 16kb or 32kb.
Tablespace type 4K page size 8K page size 16K page 32K page
limit limit size limit size limit
37
DB2 Tutorial
Storagegroups
7
This chapter describes the Database Storagegroups.
Introduction
A set of Storage paths to store database table or objects, is a storage group. You can
assign the tablespaces to the storage group. When you create a database, all the
tablespaces take default storagegorup. The default storage group for a database is
IBMSTOGROUP. When you create a new database, the default storage group is active,
if you pass the AUTOMATIC STOGROUP NO parameter at the end of CREATE
DATABASE command. The database does not have any default storage groups.
38
DB2 Tutorial
Listing storagegroups
You can list all the storagegroups in the database.
Creating a storagegroup
Here is a syntax to create a storagegroup in the database:
Syntax: [To create a new stogroup. The stogropu_name indicates name of new
storage group and path indicates the location where data (tables) are stored]
db2 create stogroup <stogroup_name> on path
Example: [To create a new stogroup stg1 on the path data1 folder]
db2 create stogroup stg1 on /data1
Output:
DB20000I The SQL command completed succesfully
Example: [To create a new tablespace named ts1 using existed storage group
stg1]
db2 create tablespace ts1 using stogroup stg1
Output:
DB20000I The SQL command completed succesfully
39
DB2 Tutorial
Altering a storagegroup
You can alter the location of a storegroup by using following syntax:
Syntax: [To shift a storage group from old location to new location]
db2 alter stogroup <sg_name> add location, location
Example: [To modify location path from old location to new location for storage
group named sg1]
db2 alter stogroup sg1 add /path/data3, /path/data4
Rebalancing a tablespace
Rebalancing the tablespace is required when we create a new folder for storagegroup
or tablespaces while the transactions are conducted on the database and the
tablespace becomes full. Rebalancing updates database configuration files with new
storagegroup.
Syntax: [To rebalance the tablespace from old storage group path to new
storage group]
db2 alter tablspace <ts_name> rebalance
Renaming a storagegroup
Syntax: [To modify the name of existing storage name]
db2 rename stogroup <old_stg_name> to <new_stg_name>
40
DB2 Tutorial
Example: [To modify the name of storage group from sg1 to new name
sgroup1]
db2 rename stogroup sg1 to sgroup1
Example: [To change from one old stogroup to new stogroup named sg2 for
tablespace ts1]
db2 alter tablespace ts1 using stogroup sg2
Step 2:
41
DB2 Tutorial
Schemas
8
This chapter introduces and describes the concept of Schema.
Introduction
A schema is a collection of named objects classified logically in the database.
In a database, you cannot create multiple database objects with same name. To do so,
the schema provides a group environment. You can create multiple schemas in a
database and you can create multiple database objects with same name, with different
schema groups.
A schema can contain tables, functions, indices, tablespaces, procedures, triggers etc.
For example, you create two different schemas named as Professional and Personal
for an employee database. It is possible to make two different tables with the same
name Employee. In this environment, one table has professional information and the
other has personal information of employee. In spite of having two tables with the
same name, they have two different schemas Personal and Professional. Hence,
42
DB2 Tutorial
the user can work with both without encountering any problem. This feature is useful
when there are constraints on the naming of tables.
Exercise
Let us create two different tables with same name but two different schemas.
Here, you create employee table with two different schemas, one for personal
and the other for professional information.
43
DB2 Tutorial
Step 2: Create two tables with the same name for Employee details
Table1: professional.employee
[To create a new table employee in the database using schema name
professional]
db2 create table professional.employee(id number, name
varchar(20), profession varchar(20), join_date date, salary
number);
Table2: personal.employee
[To create a new table employee in the same database, with schema name
personal]
db2 create table personal.employee(id number, name
varchar(20), d_birth date, phone bigint, address
varchar(200));
After executing these steps, you get two tables with same name employee, with two
different schemas.
44
DB2 Tutorial
Data Types
9
This chapter introduces various data types used in DB2.
Introduction
In DB2 Database tables, each column has its own data type depending on developers
requirements. The data type is said to be type and range of the values in columns of
a table.
o TIME: It represents the time of the day in hours, minutes and seconds.
o TIMESTAMP: It represents seven values of the date and time in the form of
year, month, day, hours, minutes, seconds and microseconds.
DATE: It represents date of the day in three parts in the form of year, month and
day.
String
o Character
o Varying length
CLOB: large object strings, you use this when a character string might exceed the
limits of the VARCHAR data type.
o Graphic
GRAHPIC
o Fixed length: Fixed length graphic string that contains double-byte characters.
o Varying length
45
DB2 Tutorial
o Binary
Signed numeric
o Exact
Binary integer
o SMALLINT [16BIT]: Using this you can insert small int values into columns.
o INTEGER [32BIT]: Using this you can insert large int values into columns.
o BIGINT [64BIT]: Using this you can insert larger int values into columns
Decimal
o DECIMAL (packed):
o DECFLOAT (decimal floating point): Using this, you can insert decimal floating
point numbers.
o Approximate
Floating points
o REAL (single precision): Using this data type, you can insert single precision
floating point numbers.
o DOUBLE (double precision): Using this data type, you can insert double
precision floating point numbers.
o XML: You can store XML data into this data type column.
46
DB2 Tutorial
Tables
10
This chapter describes tables and their types in the database.
Introduction
Tables are logical structure maintained by Database manager. In a table each
vertical block called as column (Tuple) and each horizontal block called as
row (Entity). The collection of data stored in the form of columns and rows is
known as a table. In tables, each column has different data type. Tables are
used to store persistent data.
Type of tables
Base Tables: They hold persistent data. There are different kinds of base tables,
including:
47
DB2 Tutorial
o Insert time clustering Table (ITC): Similar to MDC tables, rows are
clustered by the time they are inserted into the tables. They can be
partitioned tables. They too, do not support pureScale environment.
Creating Tables
The following syntax creates table:
48
DB2 Tutorial
Output:
DB20000I The SQL command completed successfully.
Output:
TABNAME TABSCHEMA TBSPACE
------------ ------------- --------
EMPLOYEE PROFESSIONAL TS1
1 record(s) selected.
Example: [To see the columns and data types of table employee]
db2 describe table professional.employee
Output:
49
DB2 Tutorial
5 record(s) selected.
Hidden Columns
You can hide an entire column of a table. If you call select * from query, the hidden
columns are not returned in the resulting table. When you insert data into a table, an
INSERT statement without a column list does not expect values for any implicitly
hidden columns. These type of columns are highly referenced in materialized query
tables. These type of columns do not support to create temporary tables.
50
DB2 Tutorial
Output:
Output:
CUSTID FULLNAME
----------- ------------------------
100 ravi
101 krathi
102 gopal
3 record(s) selected.
51
DB2 Tutorial
Output:
CUSTID FULLNAME PHONE
------- --------- ------------
100 ravi 9898989
101 krathi 87996659
102 gopal 768678687
3 record(s) selected.
If you want to see the data in the hidden columns, you need to execute DESCRIBE
command.
Syntax:
db2 describe table <table_name> show detail
Example:
db2 describe table professional.customer show detail
Output:
Column name Data type schema Data type name Column
column Partitionkey code
Length Scale Nulls
number sequence page Hidden Default
--------------- -------------------- --------------- -------- ----
---- -------- ---------- ------------- -------- ----------- ------
---
CUSTID SYSIBM INTEGER 4 0
No 0 0 0 No
FULLNAME SYSIBM VARCHAR 100 0
Yes 1 0 1208 No
52
DB2 Tutorial
3 record(s) selected.
Syntax:
db2 alter table <tab_name> alter column <col_name> set data type
<data_type>
Example: [To modify the data type for column id from int to bigint for
employee table]
db2 alter table professional.employee alter column id set data type
bigint
Output:
DB20000I The SQL command completed successfully.
Syntax: [To modify the column name from old name to new name of a table]
db2 alter table <tab_name> rename column <old_name> to <new_name>
Syntax:
db2 drop table <tab_name>
53
DB2 Tutorial
To delete the entire hierarchy of the table (including triggers and relation), you need
to use DROP TABLE HIERARCHY command.
Syntax:
db2 drop table hierarichy <tab_name>
54
DB2 Tutorial
Alias
11
This chapter describes the creation of alias and retrieving data using alias of database
objects.
Introduction
Alias is an alternative name for database objects. It can be used to reference the
database object. You can say, it is a nick name for database objects. Alias are defined
for the objects to make their name short, thereby reducing the query size and
increasing readability of the query.
Syntax:
db2 create alias <alias_name> for <table_name>
Syntax: [To retrieve values from a table directly with schema name]
db2 select * from <schema_name>.<table_name>
Output:
CUSTID FULLNAME PHONE
55
DB2 Tutorial
Syntax: [To retrieve values from table by calling alias name of the table]
db2 select * from <alias_name>
Example: [To retrieve values from table customer using alias name]
db2 select * from pro_cust
Output:
CUSTID FULLNAME PHONE
------- --------- ------------
100 ravi 9898989
101 krathi 87996659
102 gopal 768678687
3 record(s) selected.
56
DB2 Tutorial
Constraints
12
This chapter describes various constraints in the database.
Introduction
To enforce database integrity, a set of rules is defined, called constraints. The
constraints either permit or prohibit the values in the columns.
In a Real time database activities, the data should be added with certain restrictions.
For example, in a sales database, sales-id or transaction-id should be unique. The
constraints types are:
NOT NULL
Unique
Primary key
Foreign Key
Check
Informational
Constraints are only associated with tables. They are applied to only particular tables.
They are defined and applied to the table at the time of table creation.
Syntax:
db2 create table <table_name>(col_name col_type not null,..)
Example: [To create a sales table, with four columns (id, itemname, qty, price)
in this adding not null constraints to all columns to avoid forming any null cell
in the table.]
57
DB2 Tutorial
Output:
DB20000I The SQL command completed successfully.
Unique constraints
Using these constraints, you can set values of columns uniquely. For this, the unique
constraints are declared with not null constraint at the time of creating table.
Syntax:
58
DB2 Tutorial
Example:
db2 create table shopper.sales1(id bigint not null unique,
itemname varchar(40) not null, qty int not null,price
double not null)
Output: when you try to insert a new row with existed id value it will show this
result:
DB21034E The command was processed as an SQL statement
because it was not a
valid Command Line Processor command. During SQL
processing it returned:
SQL0803N One or more values in the INSERT statement,
UPDATE statement, or foreign key update caused by a DELETE
statement are not valid because the primary key, unique
constraint or unique index identified by "1" constrains
table "SHOPPER.SALES1" from having duplicate values for
the index key. SQLSTATE=23505
59
DB2 Tutorial
Primary key
Similar to the unique constraints, you can use a primary key and a foreign key
constraint to declare relationships between multiple tables.
Syntax:
db2 create table <tab_name>(<col> <col_type>,.., primary
key (<col>))
Foreign key
A foreign key is a set of columns in a table which are required to match at least one
primary key of a row in another table. It is a referential constraint or referential
integrity constraint. It is a logical rule about values in multiple columns in one or more
tables. It enables required relationship between the tables.
Earlier, you created a table named shopper.salesboys . For this table, the primary
key is sid. Now you are creating a new table that has sales boys personal details
with different schema named employee and table named salesboys. In this case,
sid is the foreign key.
Syntax:
db2 create table <tab_name>(<col> <col_type>,constraint
<const_name> foreign key (<col_name>)
reference <ref_table> (<ref_col>)
Example: [To create a table named salesboys with foreign key column sid]
db2 create table employee.salesboys(
sid int,
name varchar(30) not null,
phone int not null,
constraint fk_boy_id
foreign key (sid)
references shopper.salesboys (sid)
60
DB2 Tutorial
on delete restrict
)
[without error]]
db2 insert into employee.salesboys values(100,'raju',98998976),
(101,'kiran',98911176),
(102,'radha',943245176),
(103,'wali',89857330),
(104,'rayan',89851130)
Output:
DB21034E The command was processed as an SQL statement because it
was not a valid Command Line Processor command. During SQL
processing it returned: SQL0530N The insert or update value of the
FOREIGN KEY "EMPLOYEE.SALESBOYS.FK_BOY_ID" is not equal to any
value of the parent key of the parent table. SQLSTATE=23503
61
DB2 Tutorial
Checking constraint
You need to use this constraint to add conditional restrictions for a specific column in
a table.
Syntax:
db2 create table <tab_name>
(<col_name> <col_type>
name varchar(9),
hiredate date,
salary decimal(7,2),
comm decimal(7,2),
Inserting values
You can insert values into a table as shown below:
db2 insert into empl values (1,'lee', 15, 'mgr', '1985-01-01' ,
40000.00, 1000.00)
62
DB2 Tutorial
63
DB2 Tutorial
Indexes
13
This chapter covers introduction to indexes, their types, creation and dropping.
Introduction
Index is a set of pointers, which can refer to rows in a table, blocks in MDC or ITC
tables, XML data in an XML storage object that are logically ordered by the values of
one or more keys. It is created on DB2 table columns to speed up the data access for
the queries, and to cluster and partition the data efficiently. It can also improve the
performance of operation on the view. A table with a unique index can have rows with
unique keys. Depending on the table requirements, you can take different types of
indexes.
Types of indexes
Unique and Non-Unique indexes
Creating indexes
For creating unique indexes, you use following syntax:
Syntax:
db2 create unique index <index_name> on
<table_name>(<unique_column>) include (<column_names..>)
Dropping indexes
For dropping the index, you use the following syntax:
Syntax:
64
DB2 Tutorial
Example:
db2 drop index sales_index
65
DB2 Tutorial
Triggers
14
This chapter describes triggers, their types, creation and dropping of the triggers.
Introduction
A trigger is a set of actions, which are performed for responding to an INSERT, UPDATE
or DELETE operation on a specified table in the database. Triggers are stored in the
database at once. They handle governance of data. They can be accessed and shared
among multiple applications. The advantage of using triggers is, if any change needs
to be done in the application, it is done at the trigger; instead of changing each
application that is accessing the trigger. Triggers are easy to maintain and they enforce
faster application development. Triggers are defined using an SQL statement CREATE
TRIGGER.
Types of triggers
There are three types of triggers:
1. BEFORE triggers
They are executed before any SQL operation.
2. AFTER triggers
They are executed after any SQL operation.
Syntax:
db2 create sequence <seq_name>
66
DB2 Tutorial
Syntax:
db2 create trigger <trigger_name> no cascade before insert on
<table_name> referencing new as <table_object> for each row set
<table_object>.<col_name>=nextval for <sequence_name>
Syntax:
db2 select * from <tablename>
Example:
db2 select * from shopper.sales1
Output:
ID ITEMNAME QTY
------- ------------ ----------
3 bicks 100
2 bread 100
2 record(s) selected.
67
DB2 Tutorial
Syntax:
db2 create trigger <trigger_name> no cascade before insert on
<table_name> referencing new as <table_object> for each row set
<table_object>.<col_name>=nextval for <sequence_name>
Example:
db2 create trigger sales1_tri_after after insert on
shopper.sales1 for each row mode db2sql begin atomic update
shopper.sales1 set price=qty*price; end
Dropping a trigger
Here is how a database trigger is dropped:
Syntax:
db2 drop trigger <trigger_name>
Example:
68
DB2 Tutorial
Sequences
15
This chapter introduces you to the concept of sequence, creation of sequence, viewing
the sequence, and dropping them.
Introduction
A sequence is a software function that generates integer numbers in either ascending
or descending order, within a definite range, to generate primary key and coordinate
other keys among the table. You use sequence for availing integer numbers say, for
employee_id or transaction_id. A sequence can support SMALLINT, BIGINT, INTEGER,
and DECIMAL data types. A sequence can be shared among multiple applications. A
sequence is incremented or decremented irrespective of transactions.
Types of Sequences
There are two type of sequences available:
Parameters of sequences
The following parameters are used for sequences:
Data type: This is the data type of the returned incremented value. (SMALLINT,
BIGINT, INTEGER, NUMBER, DOUBLE)
START WITH: The reference value, with which the sequence starts.
Sequence cycling: the CYCLE clause causes generation of the sequence repeatedly.
The sequence generation is conducted by referring the returned value, which is stored
into the database by previous sequence generation.
69
DB2 Tutorial
Creating a sequence
You can create sequence using the following syntax:
Syntax:
Example: [To create a new sequence with the name sales1_seq and
increasing values from 1]
db2 create sequence sales1_seq as int start
with 1 increment by 1
Syntax:
db2 value <previous/next> value for <seq_name>
Output 1:
1
-----------
4
1 record(s) selected.
Syntax:
db2 drop sequence <seq_name>
70
DB2 Tutorial
Output:
DB20000I The SQL command completed successfully.
71
DB2 Tutorial
Views
16
This chapter describes introduction of views, creating, modifying and dropping the
views.
Introduction
A view is an alternative way of representing the data stored in the tables. It is not an
actual table and it does not have any permanent storage. View provides a way of
looking at the data in one or more tables. It is a named specification of a result table.
Creating a view
You can create a view using the following syntax:
Syntax:
db2 create view <view_name> (<col_name>,
<col_name1...) as select <cols>.. from
<table_name>
Modifying a view
You can modify a view using the following syntax:
Syntax:
db2 alter view <view_name> alter <col_name>
add scope <table_or_view_name>
72
DB2 Tutorial
Syntax:
db2 drop view <view_name>
Example:
db2 drop view sales1_view
73
DB2 Tutorial
Introduction
PureXML feature allows you to store well-formed XML documents in columns of
database tables. Those columns have XML database. Data is kept in its native
hierarchical form by storing XML data in XML column. The stored XML data can be
accessed and managed by DB2 database server functionality. The storage of XML data
in its native hierarchical form enables efficient search, retrieval, and update of XML. To
update a value in XML data, you need to use XQuery, SQL or combination of both.
Syntax:
By default, databases use UTF-8 (UNICODE) code set. Activate the database and
connect to it:
Syntax:
Example:
Create a well-formed XML file and create a table with data type of the column as XML.
It is mandatory to pass the SQL query containing XML syntax within double quotation
marks.
Syntax:
74
DB2 Tutorial
Example:
Insert xml values into table, well-formed XML documents are inserted into XML type
column using SQL statement INSERT.
Syntax:
Example:
<book>
<author> Gambardella Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating application
with XML</description>
</book>
</catalog>')"
Syntax:
Example:
75
DB2 Tutorial
<book>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
</book>
76
DB2 Tutorial
Introduction
Backup and recovery methods are designed to keep our information safe. In Command
Line Interface (CLI) or Graphical User Interface (GUI) using backup and recovery
utilities you can take backup or restore the data of databases in DB2 UDB.
Logging
Log files consist of error logs, which are used to recover from application errors. The
logs keep the record of changes in the database. There are two types of logging as
described below:
Circular logging
It is a method where the old transaction logs are overwritten when there is a need to
allocate a new transaction log file, thus erasing the sequences of log files and reusing
them. You are permitted to take only full back-up in offline mode. i.e., the database
must be offline to take the full backup.
Archive logging
This mode supports for Online Backup and database recovery using log files called roll
forward recovery. The mode of backup can be changed from circular to archive by
77
DB2 Tutorial
setting logretain or userexit to ON. For archive logging, backup setting database
require a directory that is writable for DB2 process.
Backup
Using Backup command you can take copy of entire database. This backup copy
includes database system files, data files, log files, control information and so on.
Offline backup
Syntax: [To list the active applications/databases]
Output:
Name Handle
Name Agents
DB2INST1 db2bp 39
*LOCAL.db2inst1.140722043938
ONE 1
Output:
db2 terminate
78
DB2 Tutorial
Example:
Output:
Online backup
To start, you need to change the mode from Circular logging to Archive Logging.
Output:
In the above output, the highlighted values are [logarchmeth1 and logarchmeth2] in
off mode, which implies that the current database in CIRCULLAR LOGGING mode. If
you need to work with ARCHIVE LOGGING mode, you need to change or add path in
the variables logarchmeth1 and logarchmeth2 present in the configuration file.
79
DB2 Tutorial
mkdir backup
mkdir backup/ArchiveDest
You can take offline backup for safety, activate the database and connect to it.
Output:
Syntax:
Example:
db2ckbkp
/home/db2inst1/ONE.0.db2inst1.DBPART000.20140722112743.001
80
DB2 Tutorial
Output:
------------------------------------------------------------
----------------
Contains 4 tablespace(s):
00001 SYSCATSPACE
00002 USERSPACE1
00003 SYSTOOLSPACE
00004 TS1
------------------------------------------------------------
----------------
Status: A
------------------------------------------------------------
----------------
81
DB2 Tutorial
Backup ID
------------------------------------------------------------
-------------------------------------------------------------
-------------------------------
Status: A
------------------------------------------------------------
----------------
EID: 4 Location:
SQLCA Information
sqlerrmc:
sqlerrp : sqlubIni
sqlstate:
82
DB2 Tutorial
------------------------------------------------------------
----------------
Contains 4 tablespace(s):
00001 SYSCATSPACE
00002 USERSPACE1
00003 SYSTOOLSPACE
00004 TS1
------------------------------------------------------------
----------------
Status: A
------------------------------------------------------------
----------------
R D 20140722114519001 F
20140722112743
------------------------------------------------------------
----------------
Contains 4 tablespace(s):
83
DB2 Tutorial
00001 SYSCATSPACE
00002 USERSPACE1
00003 SYSTOOLSPACE
00004 TS1
------------------------------------------------------------
----------------
Status: A
------------------------------------------------------------
----------------
EID: 6 Location:
Syntax:
Example:
Output:
the database on the backup image, but have matching names. The
target database
84
DB2 Tutorial
Roll forward all the logs located in the log directory, including latest changes just before
the disk drive failure.
Syntax:
Example:
Output:
Rollforward Status
Member ID = 0
85
DB2 Tutorial
Database Security
19
This chapter describes database security.
Introduction
DB2 database and functions can be managed by two different modes of security
controls:
1. Authentication
2. Authorization.
Authentication
Authentication is the process of confirming that a user logs in only in accordance with
the rights to perform the activities he is authorized to perform. User authentication can
be performed at operating system level or database level itself. By using authentication
tools for biometrics such as retina and figure prints are in use to keep the database
from hackers or malicious users.
The database security can be managed from outside the db2 database system. Here
are some type of security authentication process:
For DB2, the security service is a part of operating system as a separate product. For
Authentication, it requires two different credentials, those are userid or username, and
password.
Authorization
You can access the DB2 Database and its functionality within the DB2 database system,
which is managed by the DB2 Database manager. Authorization is a process managed
by the DB2 Database manager. The manager obtains information about the current
authenticated user, that indicates which database operation the user can perform or
access.
86
DB2 Tutorial
Secondary permission: Grants to the groups and roles if the user is a member
System-level authorization
Database-level authorization
Explain [EXPLAIN]
Authorities provide controls within the database. Other authorities for database include
with LDAD and CONNECT.
DB2 tables and configuration files are used to record the permissions associated with
authorization names. When a user tries to access the data, the recorded permissions
verify the following permissions:
87
DB2 Tutorial
While working with the SQL statements, the DB2 authorization model considers the
combination of the following permissions:
Granted to PUBLIC
Upgrade a Database
Restore a Database
Restoring Database
88
DB2 Tutorial
manager instance and its databases. These operations affect the system resources
without allowing direct access to data in the database. This authority is designed for
users to maintain databases within a database manager instance that contains
sensitive data.
Only Users with SYSMAINT or higher level system authorities can perform the following
tasks:
Taking backup
Restoring tablespaces
Reorganizing of tables
GET SNAPSHOT
LIST
o LIST APPLICATIONS
o LIST PACKAGES
o LIST TABLES
89
DB2 Tutorial
o LIST TABLESPACES
o LIST UTITLITIES
RESET MONITOR
Database authorities
Each database authority holds the authorization ID to perform some action on the
database. These database authorities are different from privileges. Here is the list of
some database authorities:
ACCESSCTRL: allows to grant and revoke all object privileges and database
authorities.
DBADM: Act as a database administrator. It gives all other database authorities except
ACCESSCTRL, DATAACCESS, and SECADM.
EXPLAIN: Allows to explain query plans without requiring them to hold the privileges
to access the data in the tables.
IMPLICIT_SCHEMA: Allows a user to create a schema implicitly by creating an object
using a CREATE statement.
Privileges
SETSESSIONUSER
Authorization ID privileges involve actions on authorization IDs. There is only one
privilege, called the SETSESSIONUSER privilege. It can be granted to user or a group
and it allows to session user to switch identities to any of the authorization IDs on
which the privileges are granted. This privilege is granted by user SECADM authority.
90
DB2 Tutorial
Schema privileges
This privileges involve actions on schema in the database. The owner of the schema
has all the permissions to manipulate the schema objects like tables, views, indexes,
packages, data types, functions, triggers, procedures and aliases. A user, a group, a
role, or PUBLIC can be granted any user of the following privileges:
DROPIN
This allows to delete the objects within the schema.
Tablespace privileges
These privileges involve actions on the tablespaces in the database. User can be
granted the USE privilege for the tablespaces. The privileges then allow them to create
tables within tablespaces. The privilege owner can grant the USE privilege with the
command WITH GRANT OPTION on the tablespace when tablespace is created. And
SECADM or ACCESSCTRL authorities have the permissions to USE privileges on the
tablespace.
CONTROL
It provides all the privileges for a table or a view including drop and grant, revoke
individual table privileges to the user.
ALTER
It allows user to modify a table.
DELETE
It allows the user to delete rows from the table or view.
INDEX: It allows the user to insert a row into table or view. It can also run import
utility.
91
DB2 Tutorial
Package privileges
User must have CONNECT authority to the database. Package is a database object that
contains the information of database manager to access data in the most efficient way
for a particular application.
CONTROL
It provides the user with privileges of rebinding, dropping or executing packages. A
user with this privileges is granted to BIND and EXECUTE privileges.
BIND
It allows the user to bind or rebind that package.
EXECUTE
Allows to execute a package.
Index privileges
This privilege automatically receives CONTROL privilege on the index.
Sequence privileges
Sequence automatically receives the USAGE and ALTER privileges on the sequence.
Routine privileges
It involves the action of routines such as functions, procedures, and methods within a
database.
92
DB2 Tutorial
Roles
20
Introduction
A role is a database object that groups multiple privileges that can be assigned to
users, groups, PUBLIC or other roles by using GRANT statement.
Restrictions on roles
A role cannot own database objects.
Permissions and roles granted to groups are not considered when you create the
following database objects.
o Views
o Triggers
o SQL Routines.
Example: [To create a new role named sales to add some table to be managed
by some user or group]
Output:
93
DB2 Tutorial
Output:
Security administrator grants role to the required users. (Before you use this
command, you need to create the users.)
Output:
Role hierarchies
For creating a hierarchies for roles, each role is granted permissions/ membership with
another role.
Syntax: [before this syntax create a new role with name of production]
94
DB2 Tutorial
LDAP
21
Introduction
LDAP is Lightweight Directory Access Protocol. LDAP is a global directory service,
industry-standard protocol, which is based on client-server model and runs on a layer
above the TCP/IP stack. The LDAP provides a facility to connect to, access, modify, and
search the internet directory.
The LDAP servers contain information which is organized in the form of a directory
tree. The clients ask server to provide information or to perform some operation on a
particular information. The server answers the client by providing required information
if it has one, or it refers the client to another server for action on required information.
The client then acquires the desired information from another server.
The tree structure of directory is maintained same across all the participating servers.
This is a prominent feature of LDAP directory service. Hence, irrespective of which
server is referred to by the client, the client always gets required information in an
error-free manner. Here, we use LDAP to authenticate IBM DB2 as a replacement of
operating system authentication.
1. Transparent
2. Plug-in
The table shown below indicates the file configuration after modification.
The text highlighted with yellow the code box means for the following:
95
DB2 Tutorial
96
DB2 Tutorial
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 400
gidNumber: 400
loginShell: /bin/csh
homeDirectory: /db2/db2my1
#
# Group: db<sid>ctl
#
dn: cn=dbmy1ctl,dc=db697,dc=example,dc=com
cn: dbmy1ctl
objectClass: top
objectClass: posixGroup
gidNumber: 404
objectClass: groupOfNames
member: uid=my1adm,cn=dbmy1adm,dc=db697,dc=example,dc=com
memberUid: my1adm
#
# User: <sid>adm
#
dn: uid=my1adm,cn=dbmy1ctl,dc=db697,dc=example,dc=com
cn: my1adm
sn: my1adm
uid: my1adm
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 404
gidNumber: 404
loginShell: /bin/csh
homeDirectory: /home/my1adm
97
DB2 Tutorial
Save the above file with name /var/lib/slapd.conf, then execute this file by following
command to add these values into LDAP Server. This is a linux command; not a db2
command.
ldapadd r- -D cn=Manager,dc=example,dc=com W f
/var/lib/slapd.conf
After registering the DB2 users and the DB2 group at the LDAP Server, logon to the
particular user where you have installed instance and database. You need to configure
LDAP client to confirm to client where your server is located, be it remote or local.
You need to change the location of server and domain information according to the
DB2 configuration. If we are using server in same system then mention it as localhost
at host and at base you can configure which is mentioned in SLAPD.conf file for
LDAP server.
You need to specify the base DN for this interface and two additional mapping
attributes. OpenLDAP client configuration file contains the entries given below:
98
DB2 Tutorial
host localhost
base dc=example,dc=com
Till this you just define the host of LDAP serve and the base DN.
Step1: Check your Local LDAP server is running. Using below command:
ps -ef | grep -i ldap
This command should list the LDAP deamon which represents your LDAP server:
/usr/lib/openldap/slapd -h ldap:/// -u ldap -g ldap -o slp=on
This indicates that you LDAP server is running and is waiting for request from clients.
If there is no such process for previous commands you can start LDAP server with the
rcldap command.
rcldap start
When the server starts, you can monitor this in the file /var/log/messages/ by issuing
the following command.
tail f /var/log/messages
LDAP server should reply with a response given below, containing all of your LDAP
entries in a LDAP Data Interchange Format(LDIF).
# extended LDIF
#
# LDAPv3
# base <> with scope subtree
# filter: (objectclass=*)
99
DB2 Tutorial
# requesting: ALL
# example.com
dn: dc=example,dc=com
dc: example
o: example
objectClass: organization
objectClass: dcObject
# search result
search: 2
result: 0 Success
# numResponses: 2
# numEntries: 1
Configuring DB2
After working with LDAP server and client, you need to configure our DB2 database for
use with LDAP. Let us discuss, how you can install and configure your database to use
our LDAP environment for the DB2 user authentication process.
group lookup
Depending upon your requirements, you can use any of the three plug-ins or all of
them. This plugin do not support environments where some users are defined in LDAP
and others in the operating Systems. If you decide to use the LDAP plug-ins, you need
to define all users associated with the database in the LDAP server. The same principle
applies to the group plug-in.
You have to decide which plug-ins are mandatory for our system. The client
authentication plug-ins used in scenarios where the user ID and the password
validation supplied on a CONNECT or ATTACH statement occurs on the client system.
So the database manager configuration parameters SRVCON_AUTH or
AUTHENTICATION need to be set to the value CLIENT. The client authentication is
difficult to secure and is not generally recommended. Server plug-in is generally
recommended because it performs a server side validation of user IDs and passwords,
if the client executes a CONNECT or ATTACH statement and this is secure way. The
server plug-in also provides a way to map LDAP user IDs DB2 authorization IDs.
Now you can start installation and configuration of the DB2 security plug-ins, you need
to think about the required directory information tree for DB2. DB2 uses indirect
authorization which means that a user belongs to a group and this group was granted
with fewer authorities. You need to define all DB2 users and DB2 groups in LDAP
directory.
100
DB2 Tutorial
# example.com
dn: dc=example,dc=com
dc: example
o: example
objectClass: organization
objectClass: dcObject
# db2 groups
dn: cn=dasadm1,dc=example,dc=com
cn: dasadm1
objectClass: top
objectClass: posixGroup
gidNumber: 300
objectClass: groupOfNames
101
DB2 Tutorial
member: uid=dasusr1,cn=dasadm1,dc=example,dc=com
memberUid: dasusr1
dn: cn=db2grp1,dc=example,dc=com
cn: db2grp1
objectClass: top
objectClass: posixGroup
gidNumber: 301
objectClass: groupOfNames
member: uid=db2inst2,cn=db2grp1,dc=example,dc=com
memberUid: db2inst2
dn: cn=db2fgrp1,dc=example,dc=com
cn: db2fgrp1
objectClass: top
objectClass: posixGroup
gidNumber: 302
objectClass: groupOfNames
member: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com
memberUid: db2fenc1
# db2 users
dn: uid=dasusr1,cn=dasadm1,dc=example,dc=com
cn: dasusr1
sn: dasusr1
uid: dasusr1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 300
gidNumber: 300
loginShell: /bin/bash
102
DB2 Tutorial
homeDirectory: /home/dasusr1
dn: uid=db2inst2,cn=db2grp1,dc=example,dc=com
cn: db2inst2
sn: db2inst2
uid: db2inst2
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 301
gidNumber: 301
loginShell: /bin/bash
homeDirectory: /home/db2inst2
dn: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com
cn: db2fenc1
sn: db2fenc1
uid: db2fenc1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 303
gidNumber: 303
loginShell: /bin/bash
homeDirectory: /home/db2fenc1
Create a file named db2.ldif and paste the above example into it. Using this file, add
the defined structures to your LDAP directory.
To add the DB2 users and DB2 groups to the LDAP directory, you need to bind the user
as rootdn to the LDAP server in order to get the exact privileges.
Execute the following syntaxes to fill the LDAP information directory with all our objects
defined in the LDIF file db2.ldif
ldapadd x D cn=Manager, dc=example,dc=com W f <path>/db2.ldif
103
DB2 Tutorial
After creating the instance user, you should have to create the file .profile and .login
in user home directory, which will be modified by DB2. To create this file in the
directory, execute the following command:
mkdir /home/db2inst2
mkdir /home/db2inst2/.login
mkdir /home/db2inst2/.profile
You have registered all users and groups related with DB2 in LDAP directory, now you
can create an instance with the name db2inst2 with the instance owner id db2inst2
and use the fenced user id db2fenc1, which is needed for running user defined
functions (UDFs)or stored procedures.
/opt/ibm/db2/V10.1/instance/db2icrt u db2fenc1 db2inst2
DBI1070I Program db2icrt completed successfully.
Now check the instance home directory. You can see new sub-directory called sqllib
and the .profile and .login files customized for DB2 usage.
cp /<db2_ldap_pakg>/<os>/v10/IBMLDAPgroups.so
/home/db2inst2/sqllib/security<bit>/plugin/group/.
Once the plug-ins are copied to the specified directory, you toned to login to DB2
instance owner and change the database manager configuration to use these plug-ins.
104
DB2 Tutorial
Su db2inst2
This modification comes into effect after you start DB2 instance. After restarting the
instance, you need to install and configure the main DB2 LDAP configuration file named
IBMLDAPSecurity.ini to make DB2 plug-ins work with the current LDAP configuration.
105
DB2 Tutorial
Now locate the file IBMLDAPSecurity.ini file in the current instance directory.
106
DB2 Tutorial
Cp
/<ibm_db_installation_directory>/db2_ldap_pkg/IBMLDAPSecurity.ini
/home/db2inst2/sqllib/cfg/
Now you need to restart your DB2 instance, using two syntaxes given below:
db2inst2> db2stop
Db2inst2> db2start
At this point, if you try db2start command, you will get security error message.
Because, DB2 security configuration is not yet correctly configured for your LDAP
environment.
Now edit IMBLDAPSecurity.ini file and type the LDAP_HOST name. The LDAP_HOST
name in both the said files must be identical.
;-----------------------------------------------------------
; SERVER RELATED VALUES
;-----------------------------------------------------------
LDAP_HOST = localhost
;-----------------------------------------------------------
; USER RELATED VALUES
----------------------------
;-------------------------------
USER_OBJECTCLASS = posixAccount
USER_BASEDN = dc=example,dc=com
USERID_ATTRIBUTE = uid
AUTHID_ATTRIBUTE = uid
;-----------------------------------------------------------
; GROUP RELATED VALUES
;-----------------------------------------------------------
GROUP_OBJECTCLASS = groupOfNames
107
DB2 Tutorial
GROUP_BASEDN = dc=example,dc=com
GROUPNAME_ATTRIBUTE = cn
GROUP_LOOKUP_METHOD = SEARCH_BY_DN
GROUP_LOOKUP_ATTRIBUTE = member
After changing these values, LDAP immediately takes effect and your DB2 environment
with LDAP works perfectly.
108