Connecting to a Database in Db2 Database Server

Summary: in this tutorial, you will learn how to connect to a database in the Db2 database server using various client tools.

Connecting to a database using the Db2 Command Line tool

First, launch the DB2 command window:

Next, type db2 command:

C:\Program Files\IBM\SQLLIB\BIN>db2

you will see the following command line processor for Db2 client appears:

db2 =>
Code language: PHP (php)

Then, use the CONNECT command to connect to a specific database e.g., the Books database:

db2 => connect to books user db2admin using your_password
Code language: PHP (php)

This command allowed us to connect to the Books database using the db2admin user with the password. You must provide the correct password for the db2admin user.

Here is the output:

Database Connection Information Database server = DB2/NT64 SQL authorization ID = DB2ADMIN Local database alias = BOOKS

After that, you can issue any SQL statement or Db2 command to interact with the Books database. For example, the following command lists all tables in the Books database:

db2 => list tables
Code language: PHP (php)

The following picture shows the output:

Finally, exit the session by using the quit command:

db2 => quit DB20000I The QUIT command completed successfully.
Code language: PHP (php)

Connecting to a database using the Db2 Command Line Plus (CLP) tool

DB2 provides a tool which is similar to SQLPlus in Oracle called Db2 Command Line Plus (or CLP) tool, which can be accessed as shown in the following screenshot:

Once you launch the CLP tool, you will see a command window with the following command:


To connect to a database, you use the connect command as follows:

SQL> connect

The CLP tool will request for the detailed information including the database, hostname, port, user (ID), and password. Press enter to accept the default value supplied in the () or provide your own values:

db2 CLP tool connect

If you provided the correct information, you should see the following message:

db2 CLP tool connect result

From now on, you can start issuing the command to interact with the Books database. For example, you can use the following statement to get the number of books:

Code language: SQL (Structured Query Language) (sql)

Here is the output:

BOOK_COUNT ----------- 1226

To close the CLP tool, you use the quit command:

SQL> quit

In this tutorial, you have learned how to connect to the Db2 database server using the Db2 Command-Line and Db2 command Line Plus tools.

Was this tutorial helpful ?