DB2 study notes memo 2018.5.9

When DB2 is installed, you choose the same option as the system user, and then when you log in, you enter the user name and password of the computer user when connecting.

1.3 DB2 database architecture

System
A system represents an installation of DB2. In a networked environment consisting of many, we sometimes refer to the system as a database partition. A system can contain multiple DB2 instances, each of which can manage one or more databases.

An instance, also known as a database manager (Database Management Application), is an in-memory image of the database manager and is the DB2 code that manages the database. Each instance is an independent operating environment that manages several databases, and a database belongs to only one instance.

Check the search order of system variables: environment variables first, then global-level registered variables, and finally instance-level registered variables.

Databases

A relational database manages data using a set of tables. A table consists of data arranged in logical relationships in rows and columns. The data in each table is logically related, and relationships can be defined between the tables.
Each database contains a set of system catalog tables (or data dictionary), configuration files and recovery logs,

  • System catalog tables are used to describe the logical and physical structure of data
  • The configuration file contains all configuration parameter values ​​assigned to the database
  • Recovery logging records in-progress transactions and archiveable transactions

Tablespaces

A tablespace is a logical middle layer between table data in a database and the database. Physical space in a database is organized as a collection of tablespaces, which are logical collections of tables. Each tablespace contains a collection of containers, a general term used to describe the allocation of physical space. Databases store data in their own tablespace containers.

Connectivity and DB2 directories

  • Node Directory: used to store all the connectivity information of the remote database.
  • System database directory (or system db directory): Contains the local database directory and the database directory mapped to the local from the remote machine.
  • Local database directory (or local db directory): Contains detailed information about the local database. An entry is added to this directory when a database is created using the create database command.

model

A schema is a result set divided by database object characteristics. Every object created in the database has schemas that are implicitly or explicitly added to the object's prefix.

Tables,indexes and large objects

Table is the basic unit of database and a description of entities in the objective world.
A table consists of rows and columns. Each column of the table describes an attribute of the corresponding entity, and the data in the same column has the same data type. Each row of the table describes information about an entity.
All database and table data are stored in tablespaces, and the data in the tables are logically related. Relationships between tables can be defined.
An index is an ordered set of pointers associated with a table, used for performance purposes and to ensure uniqueness.
Video, audio and scanned files, etc. can be stored in the database as Objects of Play (LOB).
Tables, indexes, and LOBs reside in tablespaces. To improve performance, data, index data, and object data can be stored in separate tablespaces.

view

A view is a table derived from one or several base tables, and can also be derived from other views. Views are virtual tables.

Logs

Logs are files used for recovery purposes.

Bufferpool(s)

The buffer pool is an area of ​​memory through which all index and data pages (except LOBs) must pass in order for processing. It is the primary cache used by the database manager. When it comes to database performance issues, the buffer pool is the most important object to tune.

system catalog

Each database creates and maintains a set of systematic catalog tables that describe the logical and physical structure of the data. Stored in the SYSCATSPACE tablespace.

Performance View

Performance views are used to store performance and operational information for database administrators.

Chapter 2 Creating Instances and Managing Servers

To create a database, you must create an instance, and the database is running on the instance.
A management server (DAS, Database Administrator Server) is a special type of instance that mainly performs remote management tasks.

instance concept

Instances are the intermediate logical layer between DB2's execution code and database objects.
Instances are used to provide functions such as security, communication, memory allocation, and inter-process communication for the database. The mask database is only responsible for the normal operation of the foreground, and some background things are managed by the instance.
Instances are essentially managed by a set of background processes and shared memory.
The difference between an instance and a database is that the database is physical, and our tables and indexes are stored in the database and occupy physical storage; while an instance is logical, a collection of shared memory and some configuration files (instance directories) of the process. When the instance stops, the shared memory is released and the process stops.

There are similar instance concepts in many database products: instance in Oracle, Server in Informix, Sybase, SQL Server.

Create instance

Create an instance using the db2icrt(db2 Instance CReaTe) command.
[page.33 Figure 2-1]

instance directory

The instance directory contains:

  • Database Manager Configuration File (db2systm)
  • System Database Directory (SQLDBDIR)
  • Node Directory (SQLNODIR)
  • Node configuration file (db2nodes.cfg), the db2nodes.cfg file is used to define the database partition servers participating in the DB2 instance. If you want to use tell interconnect for database partitioning.
  • Diagnostic files, database error logs, etc.

db2set command: Set DB2 level variables.
Example: View the registry variables that have been set:

db2set -all

[i] represents the variable defined on the strength level; [g] represents the global variable; [e] represents the environment variable at the operating system level.
Example: View all registry variables that can be defined in DB2:

db2set -lr

Example: Setting a specific variable at the global level

db2set DB2INSTPROF="C:\INSTDIR" -g

Example: Instance-level setting variables

db2set DB2INSTPROF="C:\MY FILES\SQLLIB" -i DB2

When the same registry variable is defined at different levels, DB2 always chooses the lowest level value.

For safety, it is recommended to always stop and start an instance after making changes to registry variables.

The db2ilist command lists DB2 instances on a machine.
The db2imigr command is used to migrate instances.
The db2iupdt command is used to update the instance configuration.

To allow/organize an instance to start automatically after every system reboot under Linux:

db2iauto -on/-off <instance name>

Start the instance: db2start

Connect to and disconnect from instances

Connect to the instance:

db2 attach to <instance name>

disconnect:

db2 detach

The db2stop command stops the instance.
db2stop forceForce stop the instance. At this time, all uncommitted applications connected to the database will be forced to roll back.

DB2INSTANCE variable

The DB2INSTANCE environment variable specifies the currently active instance to which all commands will be applied. For example, if DB2INSTANCE is set to "PROD", issuing the command "create database mydb" will create the database associated with the instance "PROD".
Use the "export" or "setenv" command to set this environment variable on Linux, and use it on Windows:

set DB2INSTANCE=DB2

View the current setting of the variable (choose one of three):

echo %DB2INSTANCE% (Windows only);echo $DB2INSTANCE (Linux/Unix)
set DB2INSTANCE
db2 get instance

Delete instance:

db2idrop <instance_name>

Configuration instance

After each instance is created, there is an instance configuration file (db2systm), which is binary and can only be modified by commands.
View the current instance configuration parameters:

db2 get dbm cfg

Update individual entries in the instance configuration file:

db2 update dbm cfg using ..

Reset the configuration parameters to the suggested defaults:

db2 reset dbm cfg

In some cases, changes to the instance configuration file take effect only after the changes are loaded into memory (that is, after db2stop is executed, and then db2start is executed).

2.2 Management server

Database Administration Server (DAS, Database Administration Server). It is a special instance that resides on the database server machine. DAS is a special DB2 administrative control point that is used to only help other DB2 servers perform remote administrative tasks.
The DB2 Administration Server (DAS) responds to requests from remote DB2 server administration tools and Configuration Assistants (CAs).
There can only be one DAS in a DB2 database server, but this DAS can manage multiple instances at the same time.

The DB2 global registry variable parameter DB2ADMINSERVERdefines the DAS that manages the DB2 database server.

1. Create a DAS on Windows

On Windows, creating a DAS requires local Administrator privileges. If a specific user account is desired, "/USER:" and "/PASSWORD:" must be used when issuing db2admin create.
There can only be one DAS in a database server. If the DAS has already been created, it needs db2admin dropto be removed by issuing.
After the DAS is created, it may be necessary to change the user ID under which the DAS service runs on Windows. Login accounts can be set or changed using the db2admin command:

db2admin setid <username> <password>

in

2. Create DAS on Linux and Unix

(1) Log in with root privileges

(2) First use operating system commands (mkuser, useradd; mkgroup, groupadd) to create DAS users and user groups and set passwords

(3) Run the dascrt command:

DB2DIR/instance/dascrt -u DASuser

Where DB2DIR is the DB2 installation directory.

Start and stop the DB2 management server

To manually start or stop DAS on Windows, you must first log on to the computer with an account or user ID that belongs to the Administrators, Server Operators, or Power Users groups.
To manually start or stop DAS on Linux, the account or user ID must be part of the dasadm_group . dasadm_group is specified in the DAS configuration parameters.
To start or stop DAS, use the db2admin startor db2admin stopcommand.

List DB2 management servers

Use the db2admin command to list the names of the DASs on the computer.

Updating DB2 Management Server (Linux)

On Linux operating systems, DB2 database products can be installed multiple times on a single machine. There can only be one DB2 management server, however, all DB2 replicas will use it. DAS can be created from any DB2 copy and will operate at the same revision level as that DB2 copy. If the DB2 copy is patched, the dasupdt command should be issued to update the DAS.
To update DAS:

(1) Log in to the computer with superuser privileges (usually as the "root" user).

(2) Issue the dasupdt command:

DB2DIR/instance/dasupdt

Use db2admin stopto stop the DAS, use the ` dasdropcommand to remove the DAS.
The dasdrop command goes out of the das subdirectory under the home directory of the DB2 management server.

Configuration Management Server

db2 get admin cfgcommand to view the current configuration parameters of DAS. db2 update admin cfg usingCommands are used to update individual entries in the DAS configuration file.
db2 reset admin cfgReset configuration parameters to recommended defaults.

Enter cmd, then enter db2cmd to enter the DB2 console.

DB2 instance

db2list: Lists all available instances on the system.
output:DB2

db2 get instance: Displays detailed information about the currently running instance.
output:当前数据库管理器实例是:DB2

set db2instance=<instance_name>: Set the instance.
Example: Schedule DB2 to current user:set db2instance=DB2

db2start: Use this command to start an instance. Before this, "set instance" needs to be run.
Normal startup will report an error, the solution: open the start menu --> IBM... There is an option to start as an administrator user, and then enter the command line.
output:SQL1026N 数据库管理器已活动。

db2stop: Stop a running instance.
output:SQL1064N DB2STOP 处理成功。

db2icrt: Create a new instance. Instance ID cannot be root id or root name.
Example: db2icrt db2inst2
Output:DB20000I DB2ICRT 命令成功完成。

DB2 database

db2 create database <database name>: Create a new database. "database_name" represents the newly created database name.
Example: db2 create database one(very slow)
output:DB20000I CREATE DATABASE 命令成功完成。

db2 create database <db_name> restrictive: Create strict database.
Example: Create a new limit database named "two": db2 create database two restrictive
Output:DB20000I CREATE DATABASE 命令成功完成。

db2 list database directory: View a list of directories available for the current instance.
output:

 系统数据库目录

 目录中的条目数 = 2

数据库 1 条目:

 数据库别名                      = TWO
 数据库名称                               = TWO
 本地数据库目录                  = C:
 数据库发行版级别                = 14.00
 注释                            =
 目录条目类型                    = 间接
 目录数据库分区号                  = 0
 备用服务器主机名                =
 备用服务器端口号                =

数据库 2 条目:

 数据库别名                      = ONE
 数据库名称                               = ONE
 本地数据库目录                  = C:
 数据库发行版级别                = 14.00
 注释                            =
 目录条目类型                    = 间接
 目录数据库分区号                  = 0
 备用服务器主机名                =
 备用服务器端口号                =

db2 activate db <db_name>: Activate the database.
Example: Activating database "one":db2 activate db one

db2 deactivate db <db_name>: Deactivate the database.
Example: Deactivate database "one":db2 deactivate db one

db2 connect to <database name>:Connect to the database.
After creating a database and putting it into use, you need to connect or start the database.
Example: Connect to database "one":db2 connect to one

db2 get db cfg for <db_name> | grep -i restrict: Verify that the database is under throttling. ("db" means database, "cfg" means configuration, 'db_name' means database name)
Example: Check if "one" database is in limit:db2 get db cfg for one | grep -i restrict

Database Manager Configuration Parameters

db2 get database manager configurationor db2 get dbm cfg: get the instance database manager information
db2 update database manager configurationor db2 update dbm cfg: update the instance database manager
db2 reset database manager configurationor db2 reset dbm cfg: reset the database manager configuration

Database configuration parameters

db2 get database configurationor db2 get db cfg: get database information
db2 update database configurationor db2 update db cfg: update database configuration
db2 reset database configurationor db2 reset db cfg: reset database configuration

db2 "call get_dbsize_info(?,?,?,-1)": check the size of the
db2 "call get_dbsize_info(?,?,?,-1)"current active database: verify the size of the current active database

Verify database permissions:
db2 "select substr(authority,1,25) as authority, d_user, d_group, d_public, role_user, role_group, role_public,d_role from table(sysproc.auth_list_authorities_for_authid('public','g'))as t order by authority"
db2 "select substr(authority,1,25) as authority, d_user, d_group, d_public, role_user, role_group, role_public,d_role from table(sysproc.auth_list_authorities_for_authid('PUBLIC','G'))as t order by authority"

db2 drop database <db_name>Remove the database from the instance.

DB2 buffer pool

db2 select * from syscat.bufferpoolsView all available buffer pools in the current database

db2 create bufferpool <bp_name> pagesize <size>: Create a buffer pool.
Example: Create a buffer pool named "bpnew" with size "8192" (8KB):db2 create bufferpool bpnew pagesize 8192

drop bufferpool <bp_name>: delete buffer pool
Example: delete a buffer pool named "bpnew":db2 drop bufferpool bpnew

DB2 storage group

db2 select * from syscat.stogroups: List all storage groups in the database.

db2 create stogroup <stogroup_name> on 'path': Create a new storage group. "stogroup_name" represents the name of the new storage group, and "path" represents the storage location of the data (table)
Example: Create a new storage group 'stg1' in the '/data1' folder:db2 create stogroup stg1 on '/data1'

db2 create tablespace <tablespace_name> using stogroup <stogroup_name>: Create a storage group tablespace
Example: Create a new tablespace named "ts1" in the storage group "stg1":db2 create tablespace ts1 using stogroup stg1

db2 alter stogroup add ‘location’, ‘location’: Move a storage group from its original location to a new location
Example:db2 alter stogroup sg1 add ‘/path/data3’, ‘/path/data4’

db2 alter stogroup drop ‘/path’: Delete folder path in storage group

db2 alter tablspace <ts_name> rebalance: Readjust the tablespace
Example:db2 alter tablespace ts1 rebalance

db2 rename stogroup <old_stg_name> to <new_stg_name>: Rename a storage group
Example: Change the name of a storage group from "sg1" to "sgroup1":db2 rename stogroup sg1 to sgroup1

db2 alter tablspace <ts_name> using stogroup <another sto_group_name>Allocate different storage groups for tablespaces.
Example: db2 alter tablespace ts1 using stogroup sg2
db2 drop stogorup <stogroup_name>: delete a storage group
Example:db2 drop stogroup stg1

DB2 schema

db2 get scheme: Get the schema of the current database. (unavailable)
db2 set schema=<schema_name>: set another mode for the current instance

db2 create schema <schema_name> authroization <inst_user>: Create new schema
Example: Create schema "schema1" in instance "db2inst2":db2 create schema schema1 authorization db2inst2

DB2 table

In a table, each vertical block is called a column (tuple), and each horizontal block is called a row (entity).

db2 create table <schema_name>.<table_name> (column_name column_type....) in <tablespace_name>: Create a new table
Example:db2 create table professional.employee(id int, name varchar(50),jobrole varchar(30),joindate date, salary double) in ts1

db2 select tabname, tabschema, tbspace from syscat.tables: View a list of tables with schema creation

db2 describe table <table_name>: View the columns and data types of the table
Example:db2 describe table professional.employee

db2 create table <tab_name> (col1 datatype,col2 datatype implicitly hidden): Create table with hidden column
Example: Create a table "customer" with hidden column "phone":db2 create table professional.customer(custid integer not null, fullname varchar(100), phone char(10) implicitly hidden)

db2 insert into <tab_name>(col1,col2,...) values(val1,val2,..): Insert data into the table
Example:db2 insert into professional.customer(custid, fullname, phone) values(100,'ravi','9898989')

db2 select * from <tab_name>: Retrieve values ​​from table
Example: Retrieve values ​​from "customer" table:db2 select * from professional.customer

db2 select col1,col2,col3 from <tab_name>: Retrieve values ​​from a table including hidden columns
Example:db2 select custid,fullname,phone from professional.customer

If you want to see the data in the hidden column, you need to execute the "DESCRIBE" command. Syntax: db2 describe table <table_name> show detail
Example:db2 describe table professional.customer show detail

db2 alter table <tab_name> alter column <col_name> set data type <data_type>: Change the type of table column
Example: Modify the column "ID" of the employee table from "int" to "bigint" type:db2 alter table professional.employee alter column id set data type bigint

db2 alter table <tab_name> rename column <old_name> to <new_name>: Modify the column name
Example: Modify the column name "fullname" of the "customers" table to "custname":db2 alter table professional.customer rename column fullname to custname

db2 drop table <tab_name>: drop table
Example: db2 drop table professional.customers
To drop a table (including triggers and relationships), you need to use the "DROP TABLE HIERARCHY" command to drop the entire hierarchy. Syntax: db2 drop table hierarchy <tab_name>
Example:db2 drop table hierarchy professional.customers

DB2 aliases

db2 create alias <alias_name> for <table_name>Create aliases for database objects
Example: Create aliases for table "prefessional.customer": db2 create alias pro_cust for professional.customer
The same result will be displayed if the database server is passed "SELECT * FROM PRO_CUST" or "SELECT * FROM PROFESSIONAL.CUSTOMER".

db2 select * from <alias_name>Create a value using the table's alias

DB2 constraints

NOT NULL: Null values ​​are prohibited.
grammar:db2 create table <table_name>(col_name col_type not null,..)

unique: Unique constraint. followed by "not null".
grammar:db2 create table <tab_name>(<col> <col_type> not null unique, ...)

primary key: Primary key.
Syntax: db2 create table <tab_name>( ,.., primary key ())
Example: Create "salesboys" table with "sid" as primary key:db2 create table shopper.salesboys(sid int not null, name varchar(40) not null, salary double not null, constraint pk_boy_id primary key (sid))

foreign key: Foreign key.
grammar:

db2 create table <tab_name>(<col> <col_type>,constraint 
<const_name> foreign key (<col_name>)  
                  reference <ref_table> (<ref_col>)

Use constraints.
grammar:

db2 create table                                                      
 (  
  primary key (),                                                       
  constraint  check (condition or condition)  
 )

example:

db2 create table empl                                                     
 (id           smallint not null,                                         
  name         varchar(9),                                                
  dept         smallint check (dept between 10 and 100), 
  job          char(5)  check (job in ('sales', 'mgr', 'clerk')), 
  hiredate     date,                                                      
  salary       decimal(7,2),                                              
  comm         decimal(7,2),                                              
  primary key (id),                                                       
  constraint yearsal check (year(hiredate) > 1986 or salary > 40500)  
 )

delete constraint

Remove the UNIQUE constraint:db2 alter table <tab_name> drop unique <const_name>

Delete the primary key:db2 alter table <tab_name> drop primary key

Remove the check constraint:db2 alter table <tab_name> drop check <check_const_name>

Remove foreign keys:db2 alter table <tab_name> drop foreigh key <foreign_key_name>

DB2 indexes

Create a unique index, syntax:

db2 create unique index <index_name> on 
<table_name>(<unique_column>) include (<column_names..>)

Example: Create an index for the shopper.sales1 table:

db2 create unique index sales1_indx on 
shopper.sales1(id) include (itemname)

To delete an index, syntax:

db2 create unique index <index_name> on 
<table_name>(<unique_column>) include (<column_names..>)

example:db2 drop index sales_index

DB2 triggers

Triggers are defined using the SQL statement "CREATE TRIGGER".

Syntax to create trigger sequence:

db2 create sequence <seq_name>

For example: trigger to create sequence for table shopper.sales1

db2 create sequence sales1_seq as int start with 1 increment by 1

grammar:

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: Create trigger shopper.sales1 table to automatically insert primary key number

db2 create trigger sales1_trigger no cascade before insert on 
shopper.sales1 referencing new as obj for each row set 
obj.id=nextval for sales1_seq

Now try to insert any value:

db2 insert into shopper.sales1(itemname, qty, price) 
values('bicks', 100, 24.00) 

Retrieve value from table, syntax:

db2 select * from <tablename>

example:db2 select * from shopper.sales1

Create an after trigger, 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

Delete trigger, syntax:

db2 drop trigger <trigger_name>

example:db2 drop trigger slaes1_trigger

DB2 sequence

Sequences are created by the CREATE SEQUENCE statement.

There are two types of sequences available:

  • NEXTVAL: It returns the incremented value of the sequence number.
  • PREVIOUS VALUE: it returns the most recently generated value

Create a sequence using the following syntax:

db2 create sequence <seq_name>

example:

db2 create sequence sales1_seq as int start 
with 1 increment by 1 

View sequence, syntax:

db2 value <previous/next> value for <seq_name>

example:db2 values previous value for sales1_seq

DROP SEQUENCE: Delete the sequence.
grammar:

db2 drop sequence <seq_name>>

Example: delete the sequence "sale1_seq" from the database:db2 drop sequence sales1_seq

DB2 view

Create a view, syntax:

db2 create view <view_name> (<col_name>,
<col_name1...) as select <cols>.. 
from <table_name>

Example: Create a view of the shopper.sales1 table:

db2 create view view_sales1(id, itemname, qty, price) 
as select id, itemname, qty, price from 
shopper.sales1

Modify the view, syntax:

db2 alter view <view_name> alter <col_name> 
add scope <table_or_view_name>

example:

db2 alter view view_sales1 alter id add 
scope shopper.sales1

To delete a view, syntax:

db2 drop view <view_name>

example:db2 drop view sales1_view

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326288708&siteId=291194637