SlideShare a Scribd company logo
JDBC - 1

JDBC
THE JAVA.SQL PACKAGE:
The java.sql package contains many classes and interfaces that are used by the JDBC API.
These classes and interfaces enable the following basic database functions: creating, opening and
managing connections to a database, executing SQL statements, processing the results in the
ResultSet, and closing the connection.
Some of the Classes and Interfaces of java.sql package are explained below:
1. The DriverManager
This class works as an interface between the application (UI) and the Microsoft Access database.
It provides the methods for managing database drivers.
getConnection(jdbc:odbc:name of DSN, <username>, <password>)
This method attempts to establish a connection to the specified database by invoking the
JDBC:ODBC bridge and by accepting the name of the DNS as an argument. The system DSN
knows where the Access database is.
Once a physical connection with a database has been established, we initialize the SQL queries
that will be used on the database.
ResultSet: The data records retrieved from the database table are held in ResultSet object. Once
the table is held in the ResultSet object, the records and the individual fields of each record can be
manipulated.
The ResultSet contains zero, one or many records. Since this object is created in memory, its
contents cannot be seen. To see the data held within the ResultSet object, its each row must be
read. We can read each record by using a while loop. The rs.next() method is used in a loop to
get one row at a time from the table.

2. Connection Interface:
A Connection object represents a connection with a database. SQL statements can be executed
and ResultSets are returned from the table.
Methods used from Connection interface:
a) void close(); The close() method will release the database resources and JDBC
resources.
b) Statement createStatement(); This method returns a new object that can be used
to execute SQL statements.
c) void close() - immediately closes the current connection and the JDBC resources it
created.
Prof. Mukesh N. Tekwani

Page 1 of 7
JDBC
3. Statement Interface:
A Statement object executes statements and obtains results after their execution. The results are in
the form of ResultSet object.
Methods used from Statement interface:
a) ResultSet executeQuery(String sqlstmt) - This method executes a SQL
query that returns a single ResultSet object.
b) int executeUpdate(String sqlstmt) - This method executes the SQL UPDATE,
DELETE or INSERT statements. It also executes the DDl statements such as CREATE
TABLE. It returns a row count or -1 for a statement without an update count.
c) int getUpdateCount – It returns the number of rows affected by the previous update
statement or -1 if the preceding statement did not have an update count.
d) boolean isClosed() – returns true if this statement is closed.

4. PreparedStatement Interface:
This interface extends the Statement interface. If a particular SQL statement has to be executed
many times, it is precompiled and stored in a PreparedStatement object. This object is then
used many times to execute the statement.
Methods used from PreparedStatement interface:
a) executeQuery() - This method executes prepared SQL query and returns a ResultSet
object..
b) executeUpdate() - This method executes the prepared SQL UPDATE, DELETE or
INSERT statements. It returns the number of rows affected. For DDL statements such as
CREATE TABLE, it returns a 0.
c) void setXxx(int n, Xxx x)– sets the value of the nth parameter to x. Xxx is data type.
d) void clearParameters() – clears all current parameters in the prepared statement.
Example: Consider a query for all books by a publisher, independent of the author. The SQL
query is:
SELECT Books.Price, Books.Title
FROM Books, Publishers
WHERE Books.Publisher_Id = Publishers.Publisher_Id
AND Publishers.Name = the name from the list box
Instead of building a separate query each time the user gives this query, we can prepare a query
with a host variable and use it many times, each time filling in a different string for the variable.
We can prepare this query as follows:
String publisherQuery =
“SELECT Books.Price, Books.Title” +
“ FROM Books, Publishers” +
“ WHERE Books.Publisher_Id = Publishers.Publisher_Id
AND Publishers.Name = ?”;
Page 2 of 7

mukeshtekwani@hotmail.com
JDBC - 1
PreparedStatement publisherQueryStat =
conn.prepareStatement(publisherQuery);
Before executing the prepared statement, we must bind the host variables to actual values with a
set method. There are different set methods for different data types. To set a string to a publisher
name:
publisherQueryStat.setString(1, publisher)
The first argument is the position number of the host variable that we want to set. The position 1
denotes the first ?. The second argument is the value we want to assign to the host variable.
Once the variables have been bound to values, we can execute the query:
ResultSet rs = publisherQueryStat.executeQuery()

5. ResultSet Interface:
The data generated by the execution of a SQL statement is stored in a ResultSet object.This
object can access only one row at a time. This row is called as its current row. When the SQL
statement is re-executed, the current recordset is closed and a new RecordSet object is created.
Methods used from ResultSet interface:
a) void close()- This method is used to release a ResutSet.
b) void getString()- This method is used to get the value of a column in the current row.
c) next() – A ResultSet is initially positioned before its first row. The first time we call the
next() method, it makes the first row as the current row. The second time we call the next()
method, the second row becomes the current row, etc
d) getXxx(int col no) and getXxx(String collabel) - it returns the value of a
column with the given column number or label, converted to the specified type. Here Xxx is a
data type such as int, double, String, Date, etc.
e) int findColumn(String colname) – gives the column index associated with a
column name.
f) boolean isClosed() – returns true if this statement is closed.
g) boolean first() and boolean last() – moves the cursor to the first or last row.
Returns true if the cursor is positioned on a row.
h) boolean isFirst() and boolean isLast()– Returns true if the cursor is positioned
on first row or last row.

6. ResultSetMetaData Interface:
This object is returned by the getMetaData() constructor. It gives information about number of
columns, their types and properties or in general about the structure of a database.
Methods used from ResultSet interface:
a) getColumnCount()- This method returns the number of columns in the ResutSet.
b) String getColumnName(int) – This method returns the name of a specific column.
c) getTableName() – This method returns the name of a table.
Prof. Mukesh N. Tekwani

Page 3 of 7
JDBC
d) DataBaseMetaData metadt = conn.getMetaData();

DATA SOURCE NAME (DSN)
If the original database is created in, say Microsoft Access, then we create a DSN. DSN stands
for Data Source Name. A DSN is itself a data structure that contains information about the
database, such as, the driver type, the database name, the actual location of the database on the
hard disk (i.e., the path), the user name and a password.
All this information in DSN is required by ODBC to drivers for creating a connection to the
database. DSN is used from an application to send or receive data to the database. DSN is stored
in the system registry.

GETTING DATA FROM COLUMNS OF A TABLE (ACCESSORS):
1. There are various accessors that permit us to read the contents of a field.
2. Each accessor has two forms, one takes a numeric argument and the other takes a string
argument.
3. When we give supply a numeric argument we are referring to the column with that number.
E.g., rs.getInt(1)returns the value of the first column.
4. When we supply a string argument we refer to the column in the result set with that
name.E.g., rs.getInt("Rollno") returns the value of the column with the name
RollNo.
5. The following are the getXXX() methods available to get the column data from the current
row:
String
boolean
int
float
byte
double
long

getString(String columnname);
getBoolean (String columnname);
getint(String columnname);
getfloat(String columnname);
getByte(String columnname);
getDouble(String columnname);
getLong(String columnname);

ACCESSING COLUMNS BY COLUMN INDEXES
Program : This program demonstrates how we can use the column indexes to identify the
columns of the current row.
stmt = conn.createStatement( );

ResultSet
rs = stmt.executeQuery(“SELECT RollNo, Name, Marks1
FROM TYBSc”);
while (rs.next())
{
int r = rs.getInt(1);
String n
= rs.getString(2);
Page 4 of 7

mukeshtekwani@hotmail.com
JDBC - 1
int m1 = rs.getInt(3);
System.out.print(r + "t");
System.out.print(n + "tt");
System.out.print(m1 + "tt");
}

TRANSACTIONS
1. A group of statements form a transaction.
2. A transaction can be committed if all the statements in the group are executed successfully. If
one statement in the group fails, the transaction can be rolled back as if none of the statements
has been issued.
3. Why should we group statements into a transaction? This is done for maintaining database
integrity. E.g., in a banking environment, if money is transferred from one account to another,
we must debit one account and simultaneously credit another account. If any one of these
transactions cannot be executed the other should also not be executed. Thus, if a debit has
taken place but the credit cannot take place, the debit statement should also be disallowed.
4. When statements are grouped in a transaction, then the transaction either succeeds in full and
it can be committed or it fails somewhere and the transaction can be rolled back (like undo
feature). This rollback will cancel all the updates to the database.
5. By default, a database connection is in autocommit mode. That is each SQL statement is
committed to the database as soon as it is executed. Once a statement is committed, you
cannot roll it back. We can turn off this default option as follows:
conn.setAutoCommit(false)
6. Example:
a. Create a Statement object as usual:
Statement stat = conn.createStatement();
b. Call executeUpdate() any number of times, as follows:
stat.executeUpdate(command1);
stat.executeUpdate(command2);
stat.executeUpdate(command3);
:
:
c. If all statements have been executed successfully, call the commit method() as
foolows:
conn.commit();
d. But if any error has occurred, we can call the rollback() command as follws:
conn.rollback();
Save Points:
We can control the position upto which we want to rollback the commands. This is done by using
save points. By creating a save point, we are marking points upto which we can later return
without abandoning the entire transaction.
Statement stat = conn.createStatement(); //start transaction; rollback goes here
Prof. Mukesh N. Tekwani

Page 5 of 7
JDBC
stat.executeUpdate(command1);
Savepoint svpt = conn.setSavePoint(); // set save point, rollback(svpt) will go here
stat.executeUpdate(command2);
if ( . . . ) conn.rollback(svp);
. . .
conn.commit();

//undo effect of command 2

If a savepoint is no longer needed, we must release it as follows:
conn.releaseSavepoint(svpt);

PROGRAMMING EXERCISES
1. Write a JDBC program to create a table GRTGS (Message – Text), insert two greetings into the table,
display the table contents, and drop the table. Assume the DSN name is GREETINGS.
2. Use JDBC API to do the following:
• Create a table in Oracle with following structure.
FriendName
Text(20)
Dob
Date
Details
Text(20)
PhoneNumber
Number
• Insert the records
• Show all the records from the table.
3. Write a program that takes values for BookName and BookId from the user on command prompt and
inserts the values in the table Book assuming table to be already created.
4. Write a program that retrieves the records from Book having field Book ,BookName and BookId
5. Write a program that searches for record in table BOOK(BookName varchar2(25),BID
number(2,5)) .The value for the BookName is taken from command prompt ,if record found “Record
Found” message is displayed and the details regarding the respective Book is displayed else “Record
Not Found” is displayed.
6. Write a JDBC program that accepts a table name and displays the total number of records in it.
7. Write a JDBC program that prints the names of all columns in a table that is given on the command
line.
8. Write a JDBC program to change the name of a column. Table name is supplied on command line.
9. Create a database “EMPLOYEEDB.MDB” through Microsoft Access. Create a Data Source Name
(DSN); give an appropriate name for DSN. Then write a single program to create a table EMPLOYEE
(ENO – Integer, ENAME-Text, BPAY-double, ALLOWANCES-double, TAX-double, NETPAYdouble). Through the same program insert 5 records, and display the output in a tabular manner.
NETPAY must be calculated and entered in the table using the formula: NETPAY = BPAY +
ALLOWANCES – TAX.
10. Write a program that accepts an employee number (ENO) for the above database and if it is found in
the table, prints its details, else prints “Record not found”.
11. Modify (alter) the above table (EMPLOYEE) so that it contains one more column called
DESIGNATION. Give appropriate SQL query to update this column. Then display all records where
designation is “Manager”.

Page 6 of 7

mukeshtekwani@hotmail.com
JDBC - 1

REVIEW QUESTIONS
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

16.

What are the components of JDBC?
Explain the three statement objects in JDBC
Explain types of execute methods in JDBC with examples.
Explain DriverManager class and its methods.
What is DSN? How is it created?
Explain steps for connectivity in JDBC
Explain any 4 methods of PreparedStatement.
Discuss the two-tier architecture for data access.
Discuss the three-tier architecture for data access. What are its advantages over the two-tier
architecture?
Differentiate between Statement and PreparedStatement
Explain different methods of ResultSet object.
State the object which encapsulates the data retrieved from the database. State the method which is
used to to get the value of the specified column of the current row from a database.
State the method which is used to get the value of the specified column of the current row from a
database.
Which method is used to execute a SELECT query? Which method is used to execute DDL statements
such as INSERT, UPDATE, and DELETE?
Write short notes on:
a. JDBC
b. JDBC-ODBC Bridge
c. Types of driver managers in JDBC
d. PreparedStatement
e. Transaction and savepoint
Explain the following method, and also state the class/interface to which they belong:
• next()
• close()
• forName()
• createStatement()
• executeUpdate()
• prepareStatement()
• getConnection()
• getString()
• getColumnCount()

Prof. Mukesh N. Tekwani

Page 7 of 7

More Related Content

What's hot (20)

PPT
Classes & objects new
lykado0dles
 
PPTX
SQL Server Select Topics
Jay Coskey
 
PDF
03 structures
Rajan Gautam
 
PDF
Data structures "1" (Lectures 2015-2016)
Ameer B. Alaasam
 
PDF
0php 5-online-cheat-sheet-v1-3
Fafah Ranaivo
 
PPT
Executing Sql Commands
phanleson
 
PPTX
Python 3.6 Features 20161207
Jay Coskey
 
PPTX
Breaking down data silos with the open data protocol
Woodruff Solutions LLC
 
PPTX
Unit ii
donny101
 
PPS
Introduction to class in java
kamal kotecha
 
PDF
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
Sagar Arlekar
 
PPTX
Chap1 array
raksharao
 
PDF
Java unit2
Abhishek Khune
 
DOC
SQL
Tuhin_Das
 
PPT
Object and class in java
Umamaheshwariv1
 
PPTX
Lecture 7 arrays
manish kumar
 
PDF
Built in classes in java
Mahmoud Ali
 
PDF
Java script introducation & basics
H K
 
PPTX
Introduction To R Language
Gaurang Dobariya
 
Classes & objects new
lykado0dles
 
SQL Server Select Topics
Jay Coskey
 
03 structures
Rajan Gautam
 
Data structures "1" (Lectures 2015-2016)
Ameer B. Alaasam
 
0php 5-online-cheat-sheet-v1-3
Fafah Ranaivo
 
Executing Sql Commands
phanleson
 
Python 3.6 Features 20161207
Jay Coskey
 
Breaking down data silos with the open data protocol
Woodruff Solutions LLC
 
Unit ii
donny101
 
Introduction to class in java
kamal kotecha
 
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
Sagar Arlekar
 
Chap1 array
raksharao
 
Java unit2
Abhishek Khune
 
Object and class in java
Umamaheshwariv1
 
Lecture 7 arrays
manish kumar
 
Built in classes in java
Mahmoud Ali
 
Java script introducation & basics
H K
 
Introduction To R Language
Gaurang Dobariya
 

Viewers also liked (18)

PDF
Java chapter 3
Mukesh Tekwani
 
PDF
Phases of the Compiler - Systems Programming
Mukesh Tekwani
 
PDF
Java chapter 1
Mukesh Tekwani
 
PDF
Html tables examples
Mukesh Tekwani
 
PDF
Html graphics
Mukesh Tekwani
 
PDF
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
PDF
Java swing 1
Mukesh Tekwani
 
DOCX
Python - Regular Expressions
Mukesh Tekwani
 
PDF
Java chapter 3 - OOPs concepts
Mukesh Tekwani
 
PDF
Digital signal and image processing FAQ
Mukesh Tekwani
 
PDF
Java chapter 5
Mukesh Tekwani
 
PDF
Jdbc 1
Mukesh Tekwani
 
PDF
Python reading and writing files
Mukesh Tekwani
 
PDF
Data Link Layer
Mukesh Tekwani
 
PDF
Chap 3 data and signals
Mukesh Tekwani
 
PDF
Data communications ch 1
Mukesh Tekwani
 
PPT
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Wayne Jones Jnr
 
PDF
Introduction to systems programming
Mukesh Tekwani
 
Java chapter 3
Mukesh Tekwani
 
Phases of the Compiler - Systems Programming
Mukesh Tekwani
 
Java chapter 1
Mukesh Tekwani
 
Html tables examples
Mukesh Tekwani
 
Html graphics
Mukesh Tekwani
 
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Java swing 1
Mukesh Tekwani
 
Python - Regular Expressions
Mukesh Tekwani
 
Java chapter 3 - OOPs concepts
Mukesh Tekwani
 
Digital signal and image processing FAQ
Mukesh Tekwani
 
Java chapter 5
Mukesh Tekwani
 
Python reading and writing files
Mukesh Tekwani
 
Data Link Layer
Mukesh Tekwani
 
Chap 3 data and signals
Mukesh Tekwani
 
Data communications ch 1
Mukesh Tekwani
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Wayne Jones Jnr
 
Introduction to systems programming
Mukesh Tekwani
 
Ad

Similar to Java 1-contd (20)

PDF
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
PPTX
Jdbc
Indu Lata
 
PPTX
Jdbc ja
DEEPIKA T
 
PPT
CS124-L9-JDBC.ppt Add more information to your upload
muzammil9676
 
PPT
JDBC JAVA DATABASE CONNECTIVITY AND JAVA
AdarshSrungarapu
 
PPTX
Module 5 jdbc.ppt
MrsRLakshmiIT
 
PDF
Java JDBC
Jussi Pohjolainen
 
PPT
Jdbc
smvdurajesh
 
PDF
Jdbc 1
Tuan Ngo
 
PPT
Executing Sql Commands
leminhvuong
 
PPTX
JDBC
Balwinder Kumar
 
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
PPTX
Jdbc presentation
nrjoshiee
 
PPT
JDBC for CSQL Database
jitendral
 
PPT
JDBC (2).ppt
manvibaunthiyal1
 
PPT
3 database-jdbc(1)
hameedkhan2017
 
PPT
JDBC.ppt JDBC_FM_2012_201JDBC_FM_2012_201
rorebik626
 
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
Jdbc
Indu Lata
 
Jdbc ja
DEEPIKA T
 
CS124-L9-JDBC.ppt Add more information to your upload
muzammil9676
 
JDBC JAVA DATABASE CONNECTIVITY AND JAVA
AdarshSrungarapu
 
Module 5 jdbc.ppt
MrsRLakshmiIT
 
Jdbc 1
Tuan Ngo
 
Executing Sql Commands
leminhvuong
 
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Jdbc presentation
nrjoshiee
 
JDBC for CSQL Database
jitendral
 
JDBC (2).ppt
manvibaunthiyal1
 
3 database-jdbc(1)
hameedkhan2017
 
JDBC.ppt JDBC_FM_2012_201JDBC_FM_2012_201
rorebik626
 
Ad

More from Mukesh Tekwani (20)

PDF
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
PPSX
Circular motion
Mukesh Tekwani
 
PPSX
Gravitation
Mukesh Tekwani
 
PDF
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
PPTX
Hexadecimal to binary conversion
Mukesh Tekwani
 
PPTX
Hexadecimal to decimal conversion
Mukesh Tekwani
 
PPTX
Hexadecimal to octal conversion
Mukesh Tekwani
 
PPTX
Gray code to binary conversion
Mukesh Tekwani
 
PPTX
What is Gray Code?
Mukesh Tekwani
 
PPSX
Decimal to Binary conversion
Mukesh Tekwani
 
PDF
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
PDF
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
PDF
Refraction of light at a plane surface
Mukesh Tekwani
 
PDF
Spherical mirrors
Mukesh Tekwani
 
PDF
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
PDF
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
PDF
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
PPSX
Cyber Laws
Mukesh Tekwani
 
PPSX
Social media
Mukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
Circular motion
Mukesh Tekwani
 
Gravitation
Mukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
Hexadecimal to binary conversion
Mukesh Tekwani
 
Hexadecimal to decimal conversion
Mukesh Tekwani
 
Hexadecimal to octal conversion
Mukesh Tekwani
 
Gray code to binary conversion
Mukesh Tekwani
 
What is Gray Code?
Mukesh Tekwani
 
Decimal to Binary conversion
Mukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
Refraction of light at a plane surface
Mukesh Tekwani
 
Spherical mirrors
Mukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
Cyber Laws
Mukesh Tekwani
 
Social media
Mukesh Tekwani
 

Recently uploaded (20)

PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
epi editorial commitee meeting presentation
MIPLM
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 

Java 1-contd

  • 1. JDBC - 1 JDBC THE JAVA.SQL PACKAGE: The java.sql package contains many classes and interfaces that are used by the JDBC API. These classes and interfaces enable the following basic database functions: creating, opening and managing connections to a database, executing SQL statements, processing the results in the ResultSet, and closing the connection. Some of the Classes and Interfaces of java.sql package are explained below: 1. The DriverManager This class works as an interface between the application (UI) and the Microsoft Access database. It provides the methods for managing database drivers. getConnection(jdbc:odbc:name of DSN, <username>, <password>) This method attempts to establish a connection to the specified database by invoking the JDBC:ODBC bridge and by accepting the name of the DNS as an argument. The system DSN knows where the Access database is. Once a physical connection with a database has been established, we initialize the SQL queries that will be used on the database. ResultSet: The data records retrieved from the database table are held in ResultSet object. Once the table is held in the ResultSet object, the records and the individual fields of each record can be manipulated. The ResultSet contains zero, one or many records. Since this object is created in memory, its contents cannot be seen. To see the data held within the ResultSet object, its each row must be read. We can read each record by using a while loop. The rs.next() method is used in a loop to get one row at a time from the table. 2. Connection Interface: A Connection object represents a connection with a database. SQL statements can be executed and ResultSets are returned from the table. Methods used from Connection interface: a) void close(); The close() method will release the database resources and JDBC resources. b) Statement createStatement(); This method returns a new object that can be used to execute SQL statements. c) void close() - immediately closes the current connection and the JDBC resources it created. Prof. Mukesh N. Tekwani Page 1 of 7
  • 2. JDBC 3. Statement Interface: A Statement object executes statements and obtains results after their execution. The results are in the form of ResultSet object. Methods used from Statement interface: a) ResultSet executeQuery(String sqlstmt) - This method executes a SQL query that returns a single ResultSet object. b) int executeUpdate(String sqlstmt) - This method executes the SQL UPDATE, DELETE or INSERT statements. It also executes the DDl statements such as CREATE TABLE. It returns a row count or -1 for a statement without an update count. c) int getUpdateCount – It returns the number of rows affected by the previous update statement or -1 if the preceding statement did not have an update count. d) boolean isClosed() – returns true if this statement is closed. 4. PreparedStatement Interface: This interface extends the Statement interface. If a particular SQL statement has to be executed many times, it is precompiled and stored in a PreparedStatement object. This object is then used many times to execute the statement. Methods used from PreparedStatement interface: a) executeQuery() - This method executes prepared SQL query and returns a ResultSet object.. b) executeUpdate() - This method executes the prepared SQL UPDATE, DELETE or INSERT statements. It returns the number of rows affected. For DDL statements such as CREATE TABLE, it returns a 0. c) void setXxx(int n, Xxx x)– sets the value of the nth parameter to x. Xxx is data type. d) void clearParameters() – clears all current parameters in the prepared statement. Example: Consider a query for all books by a publisher, independent of the author. The SQL query is: SELECT Books.Price, Books.Title FROM Books, Publishers WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = the name from the list box Instead of building a separate query each time the user gives this query, we can prepare a query with a host variable and use it many times, each time filling in a different string for the variable. We can prepare this query as follows: String publisherQuery = “SELECT Books.Price, Books.Title” + “ FROM Books, Publishers” + “ WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = ?”; Page 2 of 7 [email protected]
  • 3. JDBC - 1 PreparedStatement publisherQueryStat = conn.prepareStatement(publisherQuery); Before executing the prepared statement, we must bind the host variables to actual values with a set method. There are different set methods for different data types. To set a string to a publisher name: publisherQueryStat.setString(1, publisher) The first argument is the position number of the host variable that we want to set. The position 1 denotes the first ?. The second argument is the value we want to assign to the host variable. Once the variables have been bound to values, we can execute the query: ResultSet rs = publisherQueryStat.executeQuery() 5. ResultSet Interface: The data generated by the execution of a SQL statement is stored in a ResultSet object.This object can access only one row at a time. This row is called as its current row. When the SQL statement is re-executed, the current recordset is closed and a new RecordSet object is created. Methods used from ResultSet interface: a) void close()- This method is used to release a ResutSet. b) void getString()- This method is used to get the value of a column in the current row. c) next() – A ResultSet is initially positioned before its first row. The first time we call the next() method, it makes the first row as the current row. The second time we call the next() method, the second row becomes the current row, etc d) getXxx(int col no) and getXxx(String collabel) - it returns the value of a column with the given column number or label, converted to the specified type. Here Xxx is a data type such as int, double, String, Date, etc. e) int findColumn(String colname) – gives the column index associated with a column name. f) boolean isClosed() – returns true if this statement is closed. g) boolean first() and boolean last() – moves the cursor to the first or last row. Returns true if the cursor is positioned on a row. h) boolean isFirst() and boolean isLast()– Returns true if the cursor is positioned on first row or last row. 6. ResultSetMetaData Interface: This object is returned by the getMetaData() constructor. It gives information about number of columns, their types and properties or in general about the structure of a database. Methods used from ResultSet interface: a) getColumnCount()- This method returns the number of columns in the ResutSet. b) String getColumnName(int) – This method returns the name of a specific column. c) getTableName() – This method returns the name of a table. Prof. Mukesh N. Tekwani Page 3 of 7
  • 4. JDBC d) DataBaseMetaData metadt = conn.getMetaData(); DATA SOURCE NAME (DSN) If the original database is created in, say Microsoft Access, then we create a DSN. DSN stands for Data Source Name. A DSN is itself a data structure that contains information about the database, such as, the driver type, the database name, the actual location of the database on the hard disk (i.e., the path), the user name and a password. All this information in DSN is required by ODBC to drivers for creating a connection to the database. DSN is used from an application to send or receive data to the database. DSN is stored in the system registry. GETTING DATA FROM COLUMNS OF A TABLE (ACCESSORS): 1. There are various accessors that permit us to read the contents of a field. 2. Each accessor has two forms, one takes a numeric argument and the other takes a string argument. 3. When we give supply a numeric argument we are referring to the column with that number. E.g., rs.getInt(1)returns the value of the first column. 4. When we supply a string argument we refer to the column in the result set with that name.E.g., rs.getInt("Rollno") returns the value of the column with the name RollNo. 5. The following are the getXXX() methods available to get the column data from the current row: String boolean int float byte double long getString(String columnname); getBoolean (String columnname); getint(String columnname); getfloat(String columnname); getByte(String columnname); getDouble(String columnname); getLong(String columnname); ACCESSING COLUMNS BY COLUMN INDEXES Program : This program demonstrates how we can use the column indexes to identify the columns of the current row. stmt = conn.createStatement( ); ResultSet rs = stmt.executeQuery(“SELECT RollNo, Name, Marks1 FROM TYBSc”); while (rs.next()) { int r = rs.getInt(1); String n = rs.getString(2); Page 4 of 7 [email protected]
  • 5. JDBC - 1 int m1 = rs.getInt(3); System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); } TRANSACTIONS 1. A group of statements form a transaction. 2. A transaction can be committed if all the statements in the group are executed successfully. If one statement in the group fails, the transaction can be rolled back as if none of the statements has been issued. 3. Why should we group statements into a transaction? This is done for maintaining database integrity. E.g., in a banking environment, if money is transferred from one account to another, we must debit one account and simultaneously credit another account. If any one of these transactions cannot be executed the other should also not be executed. Thus, if a debit has taken place but the credit cannot take place, the debit statement should also be disallowed. 4. When statements are grouped in a transaction, then the transaction either succeeds in full and it can be committed or it fails somewhere and the transaction can be rolled back (like undo feature). This rollback will cancel all the updates to the database. 5. By default, a database connection is in autocommit mode. That is each SQL statement is committed to the database as soon as it is executed. Once a statement is committed, you cannot roll it back. We can turn off this default option as follows: conn.setAutoCommit(false) 6. Example: a. Create a Statement object as usual: Statement stat = conn.createStatement(); b. Call executeUpdate() any number of times, as follows: stat.executeUpdate(command1); stat.executeUpdate(command2); stat.executeUpdate(command3); : : c. If all statements have been executed successfully, call the commit method() as foolows: conn.commit(); d. But if any error has occurred, we can call the rollback() command as follws: conn.rollback(); Save Points: We can control the position upto which we want to rollback the commands. This is done by using save points. By creating a save point, we are marking points upto which we can later return without abandoning the entire transaction. Statement stat = conn.createStatement(); //start transaction; rollback goes here Prof. Mukesh N. Tekwani Page 5 of 7
  • 6. JDBC stat.executeUpdate(command1); Savepoint svpt = conn.setSavePoint(); // set save point, rollback(svpt) will go here stat.executeUpdate(command2); if ( . . . ) conn.rollback(svp); . . . conn.commit(); //undo effect of command 2 If a savepoint is no longer needed, we must release it as follows: conn.releaseSavepoint(svpt); PROGRAMMING EXERCISES 1. Write a JDBC program to create a table GRTGS (Message – Text), insert two greetings into the table, display the table contents, and drop the table. Assume the DSN name is GREETINGS. 2. Use JDBC API to do the following: • Create a table in Oracle with following structure. FriendName Text(20) Dob Date Details Text(20) PhoneNumber Number • Insert the records • Show all the records from the table. 3. Write a program that takes values for BookName and BookId from the user on command prompt and inserts the values in the table Book assuming table to be already created. 4. Write a program that retrieves the records from Book having field Book ,BookName and BookId 5. Write a program that searches for record in table BOOK(BookName varchar2(25),BID number(2,5)) .The value for the BookName is taken from command prompt ,if record found “Record Found” message is displayed and the details regarding the respective Book is displayed else “Record Not Found” is displayed. 6. Write a JDBC program that accepts a table name and displays the total number of records in it. 7. Write a JDBC program that prints the names of all columns in a table that is given on the command line. 8. Write a JDBC program to change the name of a column. Table name is supplied on command line. 9. Create a database “EMPLOYEEDB.MDB” through Microsoft Access. Create a Data Source Name (DSN); give an appropriate name for DSN. Then write a single program to create a table EMPLOYEE (ENO – Integer, ENAME-Text, BPAY-double, ALLOWANCES-double, TAX-double, NETPAYdouble). Through the same program insert 5 records, and display the output in a tabular manner. NETPAY must be calculated and entered in the table using the formula: NETPAY = BPAY + ALLOWANCES – TAX. 10. Write a program that accepts an employee number (ENO) for the above database and if it is found in the table, prints its details, else prints “Record not found”. 11. Modify (alter) the above table (EMPLOYEE) so that it contains one more column called DESIGNATION. Give appropriate SQL query to update this column. Then display all records where designation is “Manager”. Page 6 of 7 [email protected]
  • 7. JDBC - 1 REVIEW QUESTIONS 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. What are the components of JDBC? Explain the three statement objects in JDBC Explain types of execute methods in JDBC with examples. Explain DriverManager class and its methods. What is DSN? How is it created? Explain steps for connectivity in JDBC Explain any 4 methods of PreparedStatement. Discuss the two-tier architecture for data access. Discuss the three-tier architecture for data access. What are its advantages over the two-tier architecture? Differentiate between Statement and PreparedStatement Explain different methods of ResultSet object. State the object which encapsulates the data retrieved from the database. State the method which is used to to get the value of the specified column of the current row from a database. State the method which is used to get the value of the specified column of the current row from a database. Which method is used to execute a SELECT query? Which method is used to execute DDL statements such as INSERT, UPDATE, and DELETE? Write short notes on: a. JDBC b. JDBC-ODBC Bridge c. Types of driver managers in JDBC d. PreparedStatement e. Transaction and savepoint Explain the following method, and also state the class/interface to which they belong: • next() • close() • forName() • createStatement() • executeUpdate() • prepareStatement() • getConnection() • getString() • getColumnCount() Prof. Mukesh N. Tekwani Page 7 of 7