Lab 12 - Java Database Connectivity (JDBC)
Lab 12 - Java Database Connectivity (JDBC)
Lab-12
Java database connectivity (JDBC)
Lab 12: Java database connectivity (JDBC)
Table of Contents
1 Introduction 124
8 Evaluation Task (Unseen) [Expected time = 55mins for two tasks] 135
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.
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
4 Concept Map
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
Database connectivity means providing a way to be able to communicate with database 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.
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.
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.
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'
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:
int executeUpdate()
You must solve the following problems at home before the lab.
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.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.
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
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.
8. Close connection
Import java.sql;
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
Connection con=null;
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
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
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:
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
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;
switch(a)
{
case 1: // Insert New Record
{
System.out.println("Enter Name");
String s1=br.readLine();
System.out.println("Enter Address");
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");
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)
{
}
}
}
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
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
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.
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.
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.
Sample Output
name accountno balance NIC acctype
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
Sample Output
Name Company1 Company2
Ahmer Com 1 Com2
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).
10 Further Reading
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