7.Jdbc Classes and Interfaces
7.Jdbc Classes and Interfaces
18CS53
1
Course objectives: This course will enable students to
1. Provide a strong foundation in database concepts, technology, and
practice.
2. Practice SQL programming through a variety of database problems.
3. Demonstrate the use of concurrency and transactions in database
4. Design and build database applications for real world problems.
Course Outcome
Course Code Course Outcome
2
Textbooks:
1. Fundamentals of Database Systems, Ramez Elmasri and
Shamkant B. Navathe, 7th Edition, 2017,Pearson.
2. Database management systems, Ramakrishnan, and Gehrke,
3rd Edition, 2014, McGraw Hill
Reference Books:
1. Silberschatz Korth and Sudharshan, Database System
Concepts, 6th Edition, Mc-GrawHill, 2013.
2. Coronel, Morris, and Rob, Database Principles Fundamentals
of Design, Implementation and Management, Cengage
Learning 2012.
3
Prerequisite to learn
JDBC CLASSES AND INTERFACES
Students Should have the prior knowledge in
1. Basics of Java Programming language
2. DDL,DML Statement
4
JDBC CLASSES AND INTERFACES
5
JDBC CLASSES AND INTERFACES
6
Topics to be covered under JDBC Classes and
Interfaces
7
Steps for JDBC Connectivity
8
JDBC Classes and Interfaces
Steps to submit a database query:
1.Load the JDBC driver: Driver helps to make a connection to the database
hence driver must be loaded once in the program.
Class.forName()- By using this, the driver’s class file is loaded in the
memory during run time.Ex.
Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager.registerDriver()-DriverManager is an inbuilt Java class
where the register is its static member.
Ex.:DriverManager.registerDriver(new
oracle.jdbd.driver.OracleDriver());
2.Connect to the data source. -The connection object uses username,
password, and URL to set up the connection.
Connection con = DriverManager.getConnection(URL, user,
password);
9
Continue…
3.Creating Statement- The interfaces such as JDBC statement,
PreparedStatement, CallableStatement provides methods that allow a user
to send SQL statements and get data from the database
Ex. Statement stmt = con.createStatement();
4.Execute SQL statements- The SQL query is executed to interact with the
database. A query can be for updating/inserting in the database or for
retrieving data
Ex.
int n = stmt.executeUpdate(“DELETE TABLENAME”);
if(n==1)
System.out.println(“Success”);
else
System.out.println(“Failed”);
5.Closing Connection- The connection interface provides a method close() to
close the connection. Ex. con.close();
10
1.JDBC Driver Management
11
Contd…
12
Contd…
• The static method forName in the Class class returns the Java
class as specified in the argument string and executes its static
constructor.
• The static constructor of the dynamically loaded class loads an
instance of the Driver class, and this Driver object registers
itself with the DriverM
• anager class.
• The following Java example code explicitly loads a JDBC
driver:
• Class.forName("oracle/jdbc.driver.OracleDriver");
13
2.Connections
14
Example:
String url=“jdbc:oracle:www.bookstore.com:3083”;
Connection con;
try{
con = DriverManager.getConnection(url,usedId,password);
} catch SQLException excpt { …}
15
Connection Class Interface
16
Connection Class Interface
17
3.Executing SQL Statements
• PreparedStatement Class:
Precompiled, parametrized SQL statements:
– Structure is fixed
– Values of parameters are determined at run-time
18
Executing SQL Statements (Contd.)
19
4.ResultSets
ResultSet rs=pstmt.executeQuery(sql);
// rs is now a cursor
While (rs.next()) {
// process the data
}
20
ResultSets (Contd.)
21
Matching Java and SQL Data Types
SQL Type Java class ResultSet get method
BIT Boolean getBoolean()
CHAR String getString()
VARCHAR String getString()
DOUBLE Double getDouble()
FLOAT Double getDouble()
INTEGER Integer getInt()
REAL Double getFloat()
DATE java.sql.Date getDate()
TIME java.sql.Time getTime()
TIMESTAMP java.sql.TimeStamp getTimestamp()
22
ResultSet rs=stmt.executeQuery(sqIQuery);
String sqlQuerYi
ResultSet rs = stmt.executeQuery(sqIQuery) while (rs.nextO)
{
isbn = rs.getString(l);
title = rs.getString(" TITLE");
/ / process isbn and title
}
23
5.Exceptions and Warnings
24
• public String getSQLState 0 returns an SQLState identifier based on
the SQL: 1999 specifications
• public int getErrorCode () retrieves a vendor-specific error code.
• public SQLException getNextExceptionO gets the next exception in
a chain of exceptions associated with the current SQLException
object.
25
try {
stmt = con.createStatement();
warning = con.getWarnings();
while( warning != null) {
/ / handleSQLWarnings / / code to process warning
warning = warning.getNextWarningO; / /get next warning
}
con.clear\Varnings() ;
stmt.executeUpdate( queryString );
26
warning = stmt.getWarnings();
while( warning != null) {
/ / handleSQLWarnings / / code to process warning
warning = warning.getNextWarningO; / /get next warning
}
} / / end try
catch ( SQLException SQLe) {
/ / code to handle exception
} / / end catch
27
6.Examining Database Metadata
DatabaseMetaData md = con.getMetaData();
System.out.println("Driver Information:");
// print information about the driver:
System.out.println("Name:" + md.getDriverName() + "; version:"
+ mcl.getDriverVersion());
28
Database Metadata (Contd.)
DatabaseMetaData md=con.getMetaData();
ResultSet trs=md.getTables(null,null,null,null);
String tableName;
While(trs.next()) {
tableName = trs.getString(“TABLE_NAME”);
System.out.println(“Table: “ + tableName);
//print all attributes
ResultSet crs = md.getColumns(null,null,tableName, null);
while (crs.next()) {
System.out.println(crs.getString(“COLUMN_NAME” + “, “);
}
}
29
A (Semi-)Complete Example
import java.sql.*;
/*
* This is a sample program with jdbc odbc Driver
*/
public class localdemo {
public static void main(String[] args) {
try {
// Register JDBC/ODBC Driver in jdbc DriverManager
// On some platforms with some java VMs, newInstance() is
necessary...
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Test with MS Access database (sailors ODBC data source)
String url = "jdbc:odbc:mysailors";
java.sql.Connection c = DriverManager.getConnection(url);
30
A (Semi-)Complete Example cont
java.sql.Statement st = c.createStatement();
java.sql.ResultSet rs = st.executeQuery("select * from Sailors");
java.sql.ResultSetMetaData md = rs.getMetaData();
while(rs.next()) {
System.out.print("\nTUPLE: | ");
for(int i=1; i<= md.getColumnCount(); i++) {
System.out.print(rs.getString(i) + " | ");
}
}
rs.close();
} catch(Exception e) {
e.printStackTrace();
}
}
};
31
• Which of the following is advantage of using
PreparedStatement in Java?
a) Slow performance
b) Encourages SQL injection
c) Prevents SQL injection
d) More memory usage
32
• Which one of the following contains date information?
a) java.sql.TimeStamp
b) java.sql.Time
c) java.io.Time
d) java.io.TimeStamp
• Which of the following is used to call stored procedure?
a) Statement
b) PreparedStatement
c) CallableStatment
d) CalledStatement
33
Which of the following is used to rollback a JDBC transaction?
a) rollback()
b) rollforward()
c) deleteTransaction()
d) RemoveTransaction()
Which of the following is not a JDBC connection isolation
levels?
a) TRANSACTION_NONE
b) TRANSACTION_READ_COMMITTED
c) TRANSACTION_REPEATABLE_READ
d) TRANSACTION_NONREPEATABLE_READ
34
Questions
36
FDP CONTENT LINK
https://nptel.ac.in/courses/106/105/106105175/ (AICTE Approved FDP
link)
Self Assessment Quiz link
https://forms.gle/juPiZA1N6V2omoDD7
Innovative Content Link
1. https://www.youtube.com/watch?v=CAanqvvDsTw&list=PLEbnT
DJUr_Ic_9b4PcKmlae41cyxEefot&index=11
(GATE TRAINER LINK DBMS)
2. https://www.youtube.com/watch?v=5GQbACGHY_E&list=PLL_L
QvNX4xKyiExzq9GKwORoH6nvaRnOQ&index=24
(PROFESSIONAL TRAINER FOR DBMS)
3. https://www.youtube.com/watch?v=17jcw35uid0 (Practical
Tutorial)
37
References
1. https://www.digimat.in/nptel/courses/video/106105175/L21.h
tml
(NPTEL Video)
2. https://www.javatpoint.com/java-jdbc
3. Database management systems, Ramakrishnan, and Gehrke,
3rd Edition, 2014, McGraw Hill
4. https://cse.iitkgp.ac.in/~dsamanta/java/ch11.htm
5. https://www.studytonight.com/java/java-sql-package.php
6. https://www.javatpoint.com/steps-to-connect-to-the-database-
in-java
38