DB2 Example

To start and stop DB2 from cmd line:

    Initialize DB2 environment:

        Windows: run "db2cmd" as administrator.

        Linux: bash: source <DB2_instance_dir>/sqllib/db2profile; 

                  csh: source <DB2_instance_dir>/sqllib/db2cshrc 

          If you login with a DB2 admin user, the environment is already included. 

   Start DB2:

    db2start  (start DB2)

   Stop DB2:

    db2stop (stop DB2)

    db2stop force (stop DB2 and force closing all background connections)

To connect to a database:

   db2 connect to sample  (use current default OS user as DB user)

   db2 connect to sample user db2user using passwd  (login with a different user)

To run an interactive query: 

  DB2 Sample Database Schema

   Under OS terminal: 

    db2 connect to sample

    db2 "select * from db2admin.employee"  (replace "db2admin" with the schema name)

    (Note that db2admin is the schema. Ignore it if the login name is the same as the schema name).

    db2 list tables (list all tables under default schema)

    db2 list tables for all (list tables for all schemas)

   Under db2 shell:

    db2 

    connect to sample

    select * from db2admin.employee

 

To run a query in a file:

Save below SQL in a file  create.tab.

-- db2 -svtf create.tab

connect to sample;

create table tab3 (

    name varchar(20) not null,

    phone char(40),

    salary dec(7,2) 

);

select * from tab3;

Run below command:

db2 -svtf create.tab

To load a file into a table:

load from "C:\yourfilepath\censussample.dat" of del replace into db2admin.census

(Assume the data values are comma separated. )

To grant all permissions to a user (e.g., db2admin) user:

db2 GRANT DBADM,CREATETAB,BINDADD,CONNECT,CREATE_NOT_FENCED_ROUTINE,IMPLICIT_SCHEMA,LOAD,CREATE_EXTERNAL_ROUTINE,QUIESCE_CONNECT,SECADM ON DATABASE TO USER DB2ADMIN;

db2 GRANT DBADM,CREATETAB,BINDADD,CONNECT,CREATE_NOT_FENCED_ROUTINE,IMPLICIT_SCHEMA,LOAD,CREATE_EXTERNAL_ROUTINE,QUIESCE_CONNECT,SECADM ON DATABASE TO USER DB2ADMIN; 

The schema of DB2 sample database can be found here.