0% found this document useful (0 votes)
2 views

Assignment 5.Docx

The document outlines the steps to build a Java application on z/OS and integrate it with a DB2 database. It includes instructions for installing the JDBC driver, setting up the DB2 server, and writing Java code to connect to the database, create tables, and insert data. Additionally, it provides code examples for testing the connection and displaying data from the database.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Assignment 5.Docx

The document outlines the steps to build a Java application on z/OS and integrate it with a DB2 database. It includes instructions for installing the JDBC driver, setting up the DB2 server, and writing Java code to connect to the database, create tables, and insert data. Additionally, it provides code examples for testing the connection and displaying data from the database.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

ASSIGNMENT 5

NAME: Kshitija Deshmukh

PRN:22210574

Roll No:322017 DIV:B

AIM: Build an application on z/OS using java and integrate it with DB2

1)Install JDBC Driver

Create an IBM account and Install JDBC Driver


https://www.ibm.com/support/pages/db2-jdbc-driver-versions-and-downloads

Unzip and Locate the jar as C:\Program Files\IBM\SQLLIB\java\db2jcc4.jar

2)Install DB2 server using


https://www.ibm.com/docs/en/db2/11.5?topic=idds-installing-db2-database-servers-by-using-d
b2-setup-wizard-windows

Or for video reference: Install_db2_server

3)Also locate the Jar file named as db2jcc4.jar in your workspace.

4)Open the db2 command prompt and run as administrator.


Select DB2 Command Window-Administrator

Type db2.

list db2 directory will give list of all databases available. The default one is ‘SAMPLE’.

The database can be created using command – db2 create database <dbname>
Connect to the desired db using connect to <dbname> and obtain the IP address.

To get the port write following command in cmd

type C:\Windows\System32\drivers\etc\services | findstr db2c_DB2

Default port for db2 is 50000 but it might be different in some cases.(as here it’s 25000)

4)For windows, the DB2 server takes the windows authentication as the default one.

So your windows username and password is the credentials for your db2, too.

The JDBC_URL="jdbc:db2://localhost:25000/USER";

Where hostname=”localhost”

Port=25000

Dbname=USER

Username is given in user and the password in password field.

We are loading the db2 from IBM using following code :

Class.forName("com.ibm.db2.jcc.DB2Driver");

5)Java code to test connection:

Db2JdbcTest.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Db2JdbcTest {

// Use correct port 25000 as found in services file


private static final String JDBC_URL = "jdbc:db2://localhost:25000/USER";

public static void main(String[] args) {


Connection connection = null;

try {
// Load the DB2 JDBC driver
Class.forName("com.ibm.db2.jcc.DB2Driver");

// Create properties for connection


Properties props = new Properties();
props.setProperty("user", "DELL");
props.setProperty("password", "Kshitu@2211");

// Try without security mechanism property


// Or try different security mechanism values:
// props.setProperty("securityMechanism", "3"); // USER_ONLY security

System.out.println("Attempting to connect to: " + JDBC_URL);


connection = DriverManager.getConnection(JDBC_URL, props);

// Check if the connection is valid


if (connection != null && !connection.isClosed()) {
System.out.println("Connection to DB2 database is successful.");
} else {
System.out.println("Failed to connect to DB2 database.");
}

} catch (ClassNotFoundException e) {
System.err.println("DB2 JDBC Driver not found. Include the driver in
your classpath.");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL exception occurred while trying to connect to
the DB2 database.");
e.printStackTrace();
} finally {
// Close the connection
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Failed to close the connection.");
e.printStackTrace();
}
}
}
}

Compile this using:

javac -cp ".;C:\Program Files\IBM\SQLLIB\java\db2jcc4.jar" Db2JdbcTest.java

Where C:\Program Files\IBM\SQLLIB\java\db2jcc4.jar is the path where you unzipped the Jar
file.(from JDBC driver)

Run this using:

java -cp ".;C:\Program Files\IBM\SQLLIB\java\db2jcc4.jar" Db2JdbcTest

Output:

6)Java code to create tables in db2 database:


HospitalDbCreator.js

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class HospitalDbCreator {

// Use the same connection URL that worked previously


private static final String JDBC_URL = "jdbc:db2://localhost:25000/USER";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;

try {
// Load the DB2 JDBC driver
Class.forName("com.ibm.db2.jcc.DB2Driver");

// Setup connection properties


Properties props = new Properties();
props.setProperty("user", "DELL");
props.setProperty("password", "Kshitu@2211");

System.out.println("Connecting to database...");
connection = DriverManager.getConnection(JDBC_URL, props);
statement = connection.createStatement();

// Drop existing tables if they exist


try {
statement.executeUpdate("DROP TABLE PATIENTS");
System.out.println("Dropped existing PATIENTS table");
} catch (SQLException e) {
System.out.println("PATIENTS table does not exist yet");
}

try {
statement.executeUpdate("DROP TABLE DOCTORS");
System.out.println("Dropped existing DOCTORS table");
} catch (SQLException e) {
System.out.println("DOCTORS table does not exist yet");
}

try {
statement.executeUpdate("DROP TABLE HOSPITALS");
System.out.println("Dropped existing HOSPITALS table");
} catch (SQLException e) {
System.out.println("HOSPITALS table does not exist yet");
}

// Create HOSPITALS table


String createHospitalsTable =
"CREATE TABLE HOSPITALS (" +
"HOSPITAL_ID INTEGER NOT NULL PRIMARY KEY, " +
"HOSPITAL_NAME VARCHAR(50) NOT NULL, " +
"LOCATION VARCHAR(50), " +
"PHONE VARCHAR(20), " +
"BEDS INTEGER)";

statement.executeUpdate(createHospitalsTable);
System.out.println("Created HOSPITALS table");

// Create DOCTORS table


String createDoctorsTable =
"CREATE TABLE DOCTORS (" +
"DOCTOR_ID INTEGER NOT NULL PRIMARY KEY, " +
"FIRST_NAME VARCHAR(30) NOT NULL, " +
"LAST_NAME VARCHAR(30) NOT NULL, " +
"SPECIALTY VARCHAR(40), " +
"EMAIL VARCHAR(50), " +
"PHONE VARCHAR(20), " +
"HIRE_DATE DATE, " +
"SALARY DECIMAL(10,2), " +
"HOSPITAL_ID INTEGER REFERENCES HOSPITALS(HOSPITAL_ID))";

statement.executeUpdate(createDoctorsTable);
System.out.println("Created DOCTORS table");

// Create PATIENTS table


String createPatientsTable =
"CREATE TABLE PATIENTS (" +
"PATIENT_ID INTEGER NOT NULL PRIMARY KEY, " +
"FIRST_NAME VARCHAR(30) NOT NULL, " +
"LAST_NAME VARCHAR(30) NOT NULL, " +
"GENDER CHAR(1), " +
"DOB DATE, " +
"ADDRESS VARCHAR(100), " +
"PHONE VARCHAR(20), " +
"BLOOD_TYPE VARCHAR(5), " +
"ADMISSION_DATE DATE, " +
"DISCHARGE_DATE DATE, " +
"DIAGNOSIS VARCHAR(100), " +
"DOCTOR_ID INTEGER REFERENCES DOCTORS(DOCTOR_ID), " +
"HOSPITAL_ID INTEGER REFERENCES HOSPITALS(HOSPITAL_ID))";

statement.executeUpdate(createPatientsTable);
System.out.println("Created PATIENTS table");

// Insert data into HOSPITALS


String[] hospitalInserts = {
"INSERT INTO HOSPITALS VALUES (101, 'City General Hospital', 'New
York', '212-555-1000', 500)",
"INSERT INTO HOSPITALS VALUES (102, 'Mercy Medical Center',
'Chicago', '312-555-2000', 350)",
"INSERT INTO HOSPITALS VALUES (103, 'Sunrise Hospital', 'Los
Angeles', '213-555-3000', 450)",
"INSERT INTO HOSPITALS VALUES (104, 'Metro Healthcare', 'Boston',
'617-555-4000', 300)"
};

for (String sql : hospitalInserts) {


statement.executeUpdate(sql);
}
System.out.println("Inserted data into HOSPITALS table");

// Insert data into DOCTORS


String[] doctorInserts = {
"INSERT INTO DOCTORS VALUES (201, 'John', 'Smith', 'Cardiology',
'[email protected]', '212-555-1001', '2015-06-15', 250000.00, 101)",
"INSERT INTO DOCTORS VALUES (202, 'Sarah', 'Johnson',
'Neurology', '[email protected]', '312-555-2001', '2017-03-20',
275000.00, 102)",
"INSERT INTO DOCTORS VALUES (203, 'David', 'Chen', 'Pediatrics',
'[email protected]', '213-555-3001', '2016-11-05', 230000.00, 103)",
"INSERT INTO DOCTORS VALUES (204, 'Maria', 'Garcia', 'Oncology',
'[email protected]', '617-555-4001', '2018-01-10', 290000.00, 104)",
"INSERT INTO DOCTORS VALUES (205, 'Robert', 'Wilson',
'Orthopedics', '[email protected]', '212-555-1002', '2019-08-22',
260000.00, 101)",
"INSERT INTO DOCTORS VALUES (206, 'Jennifer', 'Lee',
'Dermatology', '[email protected]', '312-555-2002', '2020-05-17',
240000.00, 102)"
};

for (String sql : doctorInserts) {


statement.executeUpdate(sql);
}
System.out.println("Inserted data into DOCTORS table");

// Insert data into PATIENTS


String[] patientInserts = {
"INSERT INTO PATIENTS VALUES (301, 'Michael', 'Brown', 'M',
'1975-09-15', '123 Main St, New York, NY', '212-555-5001', 'A+', '2023-10-01',
'2023-10-05', 'Hypertension', 201, 101)",
"INSERT INTO PATIENTS VALUES (302, 'Emma', 'Davis', 'F',
'1988-04-22', '456 Park Ave, Chicago, IL', '312-555-5002', 'O-', '2023-09-28',
'2023-10-10', 'Migraine', 202, 102)",
"INSERT INTO PATIENTS VALUES (303, 'William', 'Martinez', 'M',
'1995-12-03', '789 Oak St, Los Angeles, CA', '213-555-5003', 'B+', '2023-10-02',
NULL, 'Pneumonia', 203, 103)",
"INSERT INTO PATIENTS VALUES (304, 'Sophia', 'Taylor', 'F',
'1982-07-18', '101 Pine St, Boston, MA', '617-555-5004', 'AB-', '2023-09-15',
'2023-09-25', 'Appendicitis', 204, 104)",
"INSERT INTO PATIENTS VALUES (305, 'James', 'Anderson', 'M',
'1960-11-30', '222 Elm St, New York, NY', '212-555-5005', 'A-', '2023-10-05',
NULL, 'Fracture', 205, 101)",
"INSERT INTO PATIENTS VALUES (306, 'Olivia', 'Thomas', 'F',
'1990-03-10', '333 Maple St, Chicago, IL', '312-555-5006', 'O+', '2023-09-20',
'2023-09-30', 'Eczema', 206, 102)",
"INSERT INTO PATIENTS VALUES (307, 'Benjamin', 'White', 'M',
'1979-08-25', '444 Cedar St, Los Angeles, CA', '213-555-5007', 'B-',
'2023-10-07', NULL, 'Asthma', 203, 103)",
"INSERT INTO PATIENTS VALUES (308, 'Ava', 'Harris', 'F',
'1992-01-05', '555 Birch St, Boston, MA', '617-555-5008', 'AB+', '2023-09-10',
'2023-09-20', 'Cancer', 204, 104)"
};

for (String sql : patientInserts) {


statement.executeUpdate(sql);
}
System.out.println("Inserted data into PATIENTS table");

System.out.println("Hospital database setup completed


successfully!");

} catch (ClassNotFoundException e) {
System.err.println("DB2 JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL exception occurred:");
e.printStackTrace();
} finally {
// Close resources
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
System.out.println("Database resources closed.");
} catch (SQLException e) {
System.err.println("Failed to close database resources.");
e.printStackTrace();
}
}
}
}

This will create the tables in USER Database. We can also use the ‘SYSTEM’(default) database.

Output:

6)Java code to display the db2 database we created:

HospitalDataViewer.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class HospitalDataViewer {

// Use the same connection URL that worked previously


private static final String JDBC_URL = "jdbc:db2://localhost:25000/USER";

public static void main(String[] args) {


Connection connection = null;
Statement statement = null;

try {
// Load the DB2 JDBC driver
Class.forName("com.ibm.db2.jcc.DB2Driver");

// Setup connection properties


Properties props = new Properties();
props.setProperty("user", "DELL");
props.setProperty("password", "Kshitu@2211");

System.out.println("Connecting to database...");
connection = DriverManager.getConnection(JDBC_URL, props);
statement = connection.createStatement();

// Query and display hospitals


System.out.println("\n--- HOSPITALS ---");
ResultSet hospitalRS = statement.executeQuery("SELECT * FROM
HOSPITALS ORDER BY HOSPITAL_ID");
displayResultSet(hospitalRS);
hospitalRS.close();

// Query and display doctors


System.out.println("\n--- DOCTORS ---");
ResultSet doctorRS = statement.executeQuery("SELECT * FROM DOCTORS
ORDER BY DOCTOR_ID");
displayResultSet(doctorRS);
doctorRS.close();

// Query and display patients


System.out.println("\n--- PATIENTS ---");
ResultSet patientRS = statement.executeQuery("SELECT * FROM PATIENTS
ORDER BY PATIENT_ID");
displayResultSet(patientRS);
patientRS.close();

// Query with JOIN to show doctors with their hospital


System.out.println("\n--- DOCTORS WITH HOSPITALS ---");
String doctorJoinQuery =
"SELECT D.DOCTOR_ID, D.FIRST_NAME, D.LAST_NAME, D.SPECIALTY, " +
"H.HOSPITAL_NAME, H.LOCATION " +
"FROM DOCTORS D " +
"JOIN HOSPITALS H ON D.HOSPITAL_ID = H.HOSPITAL_ID " +
"ORDER BY D.DOCTOR_ID";

ResultSet doctorJoinRS = statement.executeQuery(doctorJoinQuery);


displayResultSet(doctorJoinRS);
doctorJoinRS.close();
// Query with JOIN to show patients with their doctor and hospital
System.out.println("\n--- PATIENTS WITH DOCTORS AND HOSPITALS ---");
String patientJoinQuery =
"SELECT P.PATIENT_ID, P.FIRST_NAME, P.LAST_NAME, P.DIAGNOSIS, " +
"D.FIRST_NAME || ' ' || D.LAST_NAME AS DOCTOR_NAME, D.SPECIALTY,
" +
"H.HOSPITAL_NAME " +
"FROM PATIENTS P " +
"JOIN DOCTORS D ON P.DOCTOR_ID = D.DOCTOR_ID " +
"JOIN HOSPITALS H ON P.HOSPITAL_ID = H.HOSPITAL_ID " +
"ORDER BY P.PATIENT_ID";

ResultSet patientJoinRS = statement.executeQuery(patientJoinQuery);


displayResultSet(patientJoinRS);
patientJoinRS.close();

// Query to count patients by hospital


System.out.println("\n--- PATIENT COUNT BY HOSPITAL ---");
String countQuery =
"SELECT H.HOSPITAL_NAME, COUNT(P.PATIENT_ID) AS PATIENT_COUNT " +
"FROM HOSPITALS H " +
"LEFT JOIN PATIENTS P ON H.HOSPITAL_ID = P.HOSPITAL_ID " +
"GROUP BY H.HOSPITAL_NAME " +
"ORDER BY PATIENT_COUNT DESC";

ResultSet countRS = statement.executeQuery(countQuery);


displayResultSet(countRS);
countRS.close();

} catch (ClassNotFoundException e) {
System.err.println("DB2 JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL exception occurred:");
e.printStackTrace();
} finally {
// Close resources
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
System.out.println("Database resources closed.");
} catch (SQLException e) {
System.err.println("Failed to close database resources.");
e.printStackTrace();
}
}
}

/**
* Utility method to display a ResultSet in a formatted table
*/
private static void displayResultSet(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();

// Print column headers


for (int i = 1; i <= columnCount; i++) {
System.out.printf("%-20s", metaData.getColumnName(i));
}
System.out.println();

// Print separator line


for (int i = 1; i <= columnCount; i++) {
System.out.print("--------------------");
}
System.out.println();

// Print data rows


while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String value = rs.getString(i);
System.out.printf("%-20s", value == null ? "NULL" : value);
}
System.out.println();
}
}
}
Output:

CONCLUSION: We successfully connected DB2 with Java using JDBC driver and DB2 server.
Also ,we were able to create the databases and tables and perform CRUD operations on it.

You might also like