You are on page 1of 15

Lab Manual for Advance Computer Programming

Lab-12
Java database connectivity (JDBC)
Lab 12: Java database connectivity (JDBC)

Table of Contents
1 Introduction 124

2 Activity Time boxing 124

3 Objective of the experiment 124

4 Concept Map 125


4.1 Relational Database: 125
4.2 Database Connectivity 125
4.2.1 Establishing database connection using JDBC 125
Driver Manager 125
4.3 Structured Query language (SQL) 126
4.3.1 Executing SQL statements and processing result sets. 126
4.3.2 Executing SQL statements and processing result sets: 126

5 Homework before Lab 127


5.1 Problem Solution Modeling 127
5.1.1 Problem 1: 127
5.1.2 Problem 2: 127
5.2 Practices from home 127
5.2.1 Task-1 127

6 Procedure& Tools 128


6.1 Tools 128
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 128
6.2.1 Compile a Program 128
6.2.2 Run a Program 128
6.3 Walkthrough Task [Expected time = 30mins] 128
6.3.1 Create a database “stddb” with a table “TblStudent” before we start java database
connectivity. 128
6.3.2 Basic Steps in using JDBC: 128

7 Practice Tasks 134


7.1 Practice Task 1 [Expected time = 20mins] 134
7.2 Practice Task 2 [Expected time = 20mins] 134
7.3 Practice Task 3 [Expected time = 20mins] 134
7.4 Out comes 134
7.5 Testing 134

8 Evaluation Task (Unseen) [Expected time = 55mins for two tasks] 135

9 Evaluation criteria 135

10 Further Reading 136


10.1 Books 136
10.2 Slides 136

Department of Computer Science, Page 123


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

Lab 12: Java database connectivity JDBC

1 Introduction

In this Lab we will work on storing the data in the structured database using the bridge provided
by Java. This bridge is commonly known as JDBC. JDBC is just an acronym for Java Database
Connectivity.

JDBC provides the facility which helps your Java programs to interact with databases.In our
course we will only focus on connecting Java programs to connect to a relational database
management system. Using RDBMSdata can be stored, managed and retrieved efficiently and
securely. JDBC provides a set of mappings between SQL types and Java types. The
methodsprovided by JDBCare for transferring data between your program and the selected
database.

Relevant Lecture Material

a) Revise Lecture No. 19 and 20


b) Text Book: Java: How to Program by Paul J. Deitel, Harvey M. Deitel
1. Read pages from chapter 28

2 Activity Time boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting-up Path for JDK 5mins 5mins
6.3 Walkthrough Tasks 30mins 30mins
7 Practice tasks 20mins for each task 60mins
8 Evaluation Task 60mins for all assigned task 55mins

3 Objective of the experiment

 To understand the concept of database management systemsand the relational data model
 To use SQL to create and drop tables, and to retrieve and modify data from database
 To learn how to load appropriate driver, connect to a database, execute statements, and
process result sets using JDBC
 To use prepared statements to execute precompiled SQL statements
 To use callable statements to execute stored SQL procedures and functions

Department of Computer Science, Page 124


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

4 Concept Map

4.1 Relational Database:

Database is an application where data can be stored and retrieved as per requirement. This can be
done very rapidly as compared to files.Relational means that data is stored in highly organized
manner. All data is stored in the form of tables. Relevant data and properties are organized in one
table and others in other tables and they have specific relations with each other.One instance of
the table is one row of the table. Figure 1 shows how relationships are managed in the relational
table.

Table rows

Attributes/columns
Relational Table

Figure 1: Relationship between data

4.2 Database Connectivity

Database connectivity means providing a way to be able to communicate with database using
JDBC.

4.2.1 Establishing database connection using JDBC

First step is to establish a connection with the data source we are going to use. In this case
database connects to the Java program using the following class.

Driver Manager

This predefined and implemented class in Java connects an application to the database which is
specified by corresponding URL. When the class first attempts to establish connection with the
database, it automatically load driver for JDBC found on the path defend in the code.

Department of Computer Science, Page 125


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

4.3 Structured Query language (SQL)

SQL is a standard language for defining tables and integrity constraints andalso for accessing,
retrieving and manipulating data.SQL is universally accepted language for databases, it allows
the users to access the data in database.

4.3.1 Executing SQL statements and processing result sets.

Creating a table named "AcpStudent". having attributes firstName,lastName,birthDate,


address,phone , NIC and deptID.columns will be created for each attribute. varchar is data type
containig set of characters.

create table AcpStudent (


firstName varchar(25),
lastName varchar(25),
birthDate date,
address varchar(25),
phone char(11),
NIC char(10),
deptId char(2)
);
Retrieving data using select queries:

1. Selecting first name and last name column from table AcpStudent. All the rows will be
selected whose department id would be CS, others will be dropped out. Data will be returned in
the form of table.

select firstName, lastName from Studentwhere deptId = 'CS';

2.Selecting first name and last name column from table student. All the rows will be selected
whose department id would be CS and last name of the student will be Ali, otherrecords will be
dropped out. Data will be returned in the form of table.

select firstName, lastName from Studentwhere deptId = 'CS' and lastName = 'ali';

3.Selecting all columns from table student. All the rows will be selected whose department id
would be CS, others will be dropped out. Data will be returned in the form of table.
select * from Studentwhere deptId = 'CS'

Inserting new record in the table "NewCourse ".

insert intoNewCourse (courseId, subjectId, title)


values ('CS113', 'CS01', 'Database Systems');

4.3.2 Executing SQL statements and processing result sets:

Department of Computer Science, Page 126


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

void executeQuery( query ) method

It is used for SQL SELECT queries that returns the ResultSET object which contains the results
returned by the query and can be used to access the query results.

Example:

String query = “SELECT * from anytable”;// * means all columns


ResultSet rs = stmt.executeQuery(query); //stmt is statement object
This result set object rs will now contained the table being returned.

int executeUpdate()

It is used to execute INSERT, UPDATE or DELETE statements.

5 Homework before Lab

You must solve the following problems at home before the lab.

5.1 Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you.

5.1.1 Problem 1:

Make a list of type of statements and identify scenarios in which each should be used.

5.1.2 Problem 2:

Revise SQL from database course and all its relevant queries.

5.2 Practices from home

Solve the following subtasks.

5.2.1 Task-1

Your task is to create the complete database (ERDiagram) of a CD shop named cineMedia in
which you have to store the CD’s information. Only one copy of each cd is allowed to store in
database if CD is rented then its records removed from the catalogue table and saved in rented
video table. The user can add more CD’s records in catalogue.

Department of Computer Science, Page 127


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

6 Procedure& Tools

In this section you will be giving a step by step guide to connect to the database using Java.

6.1 Tools

Java Development Kit (JDK) 1.7

6.2 Setting-up JDK 1.7 [Expected time = 5mins]

Refer to Lab 1 sec 6.2.

6.2.1 Compile a Program

Refer to Lab 1 sec 6.2 for details.

6.2.2 Run a Program

Refer to Lab 1 sec 6.2 for details.

6.3 Walkthrough Task [Expected time = 30mins]

This task is designed to guide you towards creating and linking database with Java application.

6.3.1 Create a database “stddb” with a table “TblStudent” before we start java database
connectivity.

Follow lab instructor.

6.3.2 Basic Steps in using JDBC:

1. Import required packages


2. Load Driver
3. Define Connection URL
4. Establish Connection
5. Create a Statement Object
6. Execute Query/DML
7. Process Result

Department of Computer Science, Page 128


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

8. Close connection

6.3.2.1 Import required packages

Import java.sql;

6.3.2.2 Load Driver

We need to load relevant driver for data base. Different drivers for different databases are
available.Use appropriate one according to your database.

For MS Access
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”)
For MySQL
Class.forName(“com.mysql.jdbc.Driver”)

6.3.2.3 Define Connection URL, UserName and Password for the database

To get a Connection object, we need to specify URL of database.


If we are using MySQL jdbc driver we need to create a database in MySQL.

String db_connURL= "jdbc:mysql://localhost:3306/stddb";


String db_username = “root”;
String db_password = “”;

6.3.2.4 Establish Connection

Connection con=null;

Use DeviceManager to get the connection object


Connection conn =DriverManager.getConnection(db_connURL, db_username,
db_password);

public static Connection getConnection(String url, String user, String password) throws


SQLException

This method attempt to create a connection to the given database using URL. The
DriverManager selects an appropriate driver from the set of registered JDBC drivers.
Parameters:
url - a database url of the form jdbc
username – user name of the database server

Department of Computer Science, Page 129


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

password – password of the database server


Returns: a connection to the URL

6.3.2.5 Create a Statement Object

A Statement object is obtained from a Connection object using its method createStatement() .
Statement stmt = con.createStatement( );
Once you have a statement, you can use it for various kinds of SQL queries

6.3.2.6 Execute Query/DML

Now we need to pass the SQL statements and to execute them with one of the methods
defined for executing queries.Two methods are generally used for executing SQL queries.
These are as following:

void executeQuery( query ) method


It is used for SQL SELECT queries that returns the ResultSET object which contains the
results returned by the query and can be used to access the query results.
Example:
String query = “SELECT * from anytable”;// * means all columns
ResultSet rs = stmt.executeQuery(query); //stmt is statement object
This result set object rs willnow contained the table being returned.

int executeUpdate()
It is used to execute INSERT, UPDATE or DELETE statements.
.
Insert into
It returns an Integer value which repesents the number of rows updated
String sql = “INSERT INTO tablename ” + “(columnNames) Values (values)” ;
int count = stmt.executeUpdate(sql);
Result set:
The ResultSet provides various getXXX methods that takes a column index or name and
returns the relevant data. XXX is replaced by the data type of the data to be retirieved.
The ResultSet keep the data in the form tables (rows & columns) First row has index 1, not 0
as was in arrays.
The next method of ResultSet returns true or false depending upon whether the data for next
row is available or not and moves the cursor to the next row. Always remember to call next()
method at-least once after retrieving data from one row. To access the data of the
columnsfrom the current row you need to use various getters providedby the ResultSet class.

For example, the following code will iterate over the whole ResultSet row wise and
illustrates the usage of getters methods for each column in a single row
while ( rs.next() ){ // for moving to next row
String name = rs.getString(“columnName”); //by using column name

Department of Computer Science, Page 130


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

String name = rs.getString(1); // or by using column index in the table in database


}

6.3.2.7 Close connection

An opening connection is expensive. Delay this step if more database operations are expected
con.close();

Final code:

import java.sql.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class StudentClass


{
public static void main(String [] args)
{
try
{
int a;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Scanner s=new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
String url=" jdbc:mysql://localhost:3306/stddb";
Connection con=DriverManager.getConnection(url);

System.out.println("Enter 1 for Insert Record");


System.out.println("Enter 2 for Delete Record");
System.out.println("Enter 3 for Update Record");
System.out.println("Enter 4 for View Record by ID No");
System.out.println("Enter 5 for View All Records");
System.out.println("Enter choice");
a=s.nextInt();

switch(a)
{
case 1: // Insert New Record
{
System.out.println("Enter Name");
String s1=br.readLine();
System.out.println("Enter Address");

Department of Computer Science, Page 131


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

String s2=br.readLine();
String p="INSERT INTO TblStudent (Name,Address)
VALUES(?,?)";
PreparedStatement st=con.prepareStatement(p);
st.setString(1,s1);
st.setString(2,s2);
int i=st.executeUpdate();
//ResultSet i=st.executeQuery();
if(i==1)
System.out.println("Success");
con.close();
break;
}
case 2: // Delete Existing Record
{
System.out.println("Enter ID");
String s1=br.readLine();
String p="DELETE FROM TblStudent WHERE ID = ?";
PreparedStatement st=con.prepareStatement(p);
st.setString(1,s1);
int i=st.executeUpdate();
//ResultSet i=st.executeQuery();
if(i==1)
System.out.println("Success");
if(i==0)
System.out.println("Record not found!");
con.close();
break;
}
case 3:
{
System.out.println("Enter record ID to update: ");
String s1=br.readLine();
System.out.println("Enter Name");
String s2=br.readLine();
System.out.println("Enter Address");
String s3=br.readLine();
String p="Update TblStudent SET Name=?,Address=?
WHERE ID=?";
PreparedStatement st=con.prepareStatement(p);
st.setString(1,s2);
st.setString(2,s3);
st.setString(3,s1);

int i=st.executeUpdate();
if(i==1)
System.out.println("Success");

Department of Computer Science, Page 132


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

con.close();
break;
}
case 4:
{
System.out.println("Enter ID");
String s1=br.readLine();
String p="Select * FROM TblStudent WHERE ID = "+s1;
Statement st=con.createStatement();
//int i=st.executeQuery();
ResultSet i=st.executeQuery(p);

while(i.next())
{
System.out.println(i.getString(2));
System.out.println(i.getString(3));
}

con.close();
break;
}
case 5:
{
String p="Select * FROM TblStudent";
Statement st=con.createStatement();
//int i=st.executeQuery();
ResultSet i=st.executeQuery(p);

while(i.next())
{
System.out.print(i.getString(2)+" ");
System.out.println(i.getString(3));
}

con.close();
break;
}
}
}
catch(Exception p)
{
}
}
}

Department of Computer Science, Page 133


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

7 Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Advanced Computer Programming\Lab10

7.1 Practice Task 1 [Expected time = 20mins]

Create a class of BankAccounts having attributes name, accountNo, balance, NIC, accountType,
date. You have to save the data in database. Bank accounts are two different types.

1 Student account
2 General account

The data according to type must be managed in database.

7.2 Practice Task 2 [Expected time = 20mins]

Extend the Practice Task 1for the scenario where the user wants to update/delete the records then
save those records in another table with updated data. For searching record you it is a
requirement to use prepared statements.

7.3 Practice Task 3 [Expected time = 20mins]

Create two different type of companies in which both companies have same tiles for designations
and both companies have their own databases. Create the employee’s records. Your task is to
generate the list of those employees that work in both companies. Display such record on the
screen and change the status of those employees who meet the criteria.

7.4 Out comes

After completing this lab, student will be able to understand how database transactions are
performed using JDBC.

7.5 Testing

This section provides you the test cases to test the working of your program. If you get the
desired mentioned outputs for the given set of inputs then your program is right.

Department of Computer Science, Page 134


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

Test Cases for Practice Task-1

Sample Output
name accountno balance NIC acctype

Test Cases for Practice Task-2

Sample Output
nam accountn balanc NIC acctyp
e o e e
ali 123 2000 1234567- S
9

Updated table
name accountno balance NIC acctype
ali 123 3000 1234567 S
-9

Test Cases for Practice Task-3

Sample Output
Name Company1 Company2
Ahmer Com 1 Com2

8 Evaluation Task (Unseen) [Expected time = 55mins for two tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

9 Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

Department of Computer Science, Page 135


C.U.S.T.
Lab 12: Java database connectivity (JDBC)

10 Further Reading

This section provides the references to further polish your skills.

10.1 Books

Text Book:
 Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
 Java Beginners Guide: http://www.oracle.com/events/global/en/java-outreach/resources/java-a-
beginners-guide-1720064.pdf
 http://exampledepot.8waytrips.com/ for the package by package examples
 Study the SQL API to change the driver to establish the connection with MySQL and Oracle.

10.2 Slides

The slides and reading material can be accessed from the folder of the class instructor available
at \\dataserver\jinnah$\

Osama Mohd
Usama Bin Khurshid
Yaseen
Iftikhar bilal
Umair tahir
Ahmed kamal
Bilal zameer
Israr ul haq

Department of Computer Science, Page 136


C.U.S.T.

You might also like