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

interacting with database self notes

The document provides an overview of JDBC (Java Database Connectivity) and its architecture, detailing the types of JDBC drivers and their functionalities. It explains the core JDBC classes and interfaces, including DriverManager, Connection, Statement, and ResultSet, along with their roles in database interaction. Additionally, it discusses the two-tier and three-tier models of JDBC architecture and the importance of using PreparedStatement for secure SQL queries.

Uploaded by

hj05102006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

interacting with database self notes

The document provides an overview of JDBC (Java Database Connectivity) and its architecture, detailing the types of JDBC drivers and their functionalities. It explains the core JDBC classes and interfaces, including DriverManager, Connection, Statement, and ResultSet, along with their roles in database interaction. Additionally, it discusses the two-tier and three-tier models of JDBC architecture and the importance of using PreparedStatement for secure SQL queries.

Uploaded by

hj05102006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

5.

Interacting with database

5.1 : Introduction to JDBC, ODBC.


5.2 JDBC Architecture: Two-tier and three-tier models.
5.3 Types of JDBC Drivers.
5.4 Driver Interfaces and Driver Manager class: Connection Interface, Statement Interface,
Prepared Statement Interface, ResultSet Interface.
5.5 The essential JDBC Program.
5.1 : Introduction to JDBC, ODBC.

1. ODBC (Open Database Connectivity)


- ODBC is an API (Application Programming Interface) that allows applications to access data in a
Database Management System (DBMS), ), regardless of the database type (like SQL Server, MySQL,
Oracle, etc.).
- It was created by Microsoft to enable applications to connect to different databases using a common
set of commands.
- Working:
- It’s platform-independent, meaning an application can use ODBC to connect to various types of
databases without worrying about specific database languages or differences.
2. JDBC (Java Database Connectivity)
- Definition: JDBC is also an API, but it is specific to Java. JDBC provides a standard way for Java
applications to interact with databases.
- Purpose: JDBC allows Java programs to connect to databases, send SQL statements, and retrieve data.
- Working:
- JDBC uses Java classes and interfaces to establish a connection, send SQL commands, and handle the
results.
- Through JDBC, a Java application can connect to various databases using JDBC drivers (similar to ODBC
drivers, but specifically designed for Java).
- The JDBC specification is created by Sun Microsystems (now Oracle).
- Third-party vendors (like Oracle, MySQL, etc.) can create JDBC drivers following this specification. These
drivers are used by developers to enable database connectivity in Java applications.
- Why JDBC?: JDBC is tailored for Java applications and integrates well with Java’s platform-independent
nature. It ensures that Java programs can interact with databases efficiently.
- ODBC is for general database connectivity across multiple programming languages.
- JDBC is specifically for Java applications and provides a standardized way to interact with databases
using SQL.
- JDBC is specially used for having connectivity with the RDBMS package (such as oracle or mysql)
Using corresponding jdbc driver

5.2 JDBC Architecture: Two-tier and three-tier models.


- JDBC Architecture supports both two tier and three tier processing model

Two tier model


- In the Two-Tier Model, a Java application directly connects and communicates with the database.
- To facilitate this direct connection, a JDBC driver is used, which provides the necessary classes and
methods to interact with the database.
- This model is commonly used for standalone applications where the application itself handles data
access directly without any intermediary server.

Three-Tier Model
- In the Three-Tier Model, there is an extra layer between the Java application and the database.
- Client layer: The front end, often an HTML browser, sends requests.
- Middle layer (Application layer): The Java application receives the client’s request and processes it.
- Database layer: The application layer uses JDBC to communicate with the database.
- This model is commonly used in web applications where the browser sends requests to a server, which then
communicates with the database through JDBC.

- 5.2.3 How JDBC Works?


 The Java application establishes a connection to the database using the JDBC driver.
 The application uses JDBC classes and interfaces to send SQL queries and retrieve results.
 The JDBC driver communicates with the database and executes the SQL commands.
 Results are sent back to the Java application, which then processes them further.

5.3 Types of JDBC Drivers.

- There are four types of JDBC drivers, each with distinct advantages and limitations.
Type 1: JDBC-ODBC Bridge Driver
 This driver acts as a bridge by translating JDBC calls into ODBC calls. It then uses the ODBC driver to
connect to the database.
1. Requires the ODBC driver and the native database connectivity on the client machine.

2. A Java program cannot directly communicate with an ODBC driver because

ODBC written in C language


 Pros: Allows connectivity to almost any database using the ODBC standard.
 Cons:
o This driver is slow because each JDBC call has to pass through the ODBC layer.
o It’s not suitable for large-scale applications because of performance limitations.
o The ODBC driver must be installed on every client machine.
o Deprecated in Java 8 and later.

Type 2: Native-API/Partly Java Driver


 Converts JDBC calls into native database API calls using native libraries. Requires database-specific
native drivers to be installed on the client.

 Pros: Faster than the Type 1 driver since JDBC calls are
directly converted to database-specific calls.
 Cons:
o Platform-dependent: Works only on systems where native drivers are available.
o Requires native libraries, which complicates deployment.
Type 3: All Java/Net /Network Protocol Driver for Accessing Middleware Server
 How It Works:
o Converts JDBC calls into a database-independent protocol, which is sent to a middleware
server.
o The middleware server (which could be a dedicated server or application server) then
translates these JDBC calls into database-specific protocols to interact with the database.

 Features:
o It is server-based, which means there’s no need for database-specific libraries on the client
side.
o Commonly used in internet applications since the client only communicates with the
middleware, making it easy to access databases over
networks.

 Merits:
No need to install client-side libraries.
Suitable for web-based applications.
Can connect to multiple databases using the same driver.
Disadvantages :
Performance depends on the middleware server.
Requires a dedicated middleware server.
Type 4: All Java/Native-Protocol Pure Driver/thin driver
 How It Works:
o Type 4 drivers convert JDBC calls directly into the database’s network protocol.
o This allows direct communication between the client application and the database server
without any intermediate translation or middleware layer.
 Features:
o Also known as a “Pure Java driver” because it’s entirely implemented in Java.
o Platform-independent and suitable for use over the internet, making it very versatile for
Java-based applications.
 Merits:
1. Platform-Independent: Platform-independent: Works on any system with Java installed.
2. High Performance: High performance as it eliminates additional layers.
3. No Client-Side Installation Needed: Since it doesn’t require any native database libraries on the
client side, it’s easy to deploy and maintain.
4. Dynamic Downloading: Type 4 drivers can be downloaded at runtime, allowing for flexibility in web-
based applications.
 Demerits:
o Database-Specific: Type 4 drivers are typically created for a specific database, so you might
need a different driver for each database you connect to.
5.4.1 Core JDBC Classes and Interfaces
The JDBC API, used for database connectivity in Java, is part of the java.sql and javax.sql packages. Key
elements include:
1. DriverManager (class)- Manages JDBC drivers and establishes connections to databases.
2. Connection - Represents the connection to a specific database.
3. Statement - Used for executing SQL statements.
4. ResultSet - Holds the data returned by a SQL query.
In every JDBC-based Java program, the statement import java.sql.*; imports these core JDBC classes and
interfaces.
5.4.2 DriverManager Class

 - Purpose:
o Manages a list of database drivers.
o Establishes a connection between a Java application and a database.
 Key Methods:
o static Connection getConnection(String url): Establishes a connection to the database.
o void registerDriver(Driver driver): Registers a driver with DriverManager.

// Step 1: Load the JDBC driver


Class.forName("com.mysql.cj.jdbc.Driver
");
o dynamically assing kela jail
Note : connection method connection establish karnasathi use hote tar driver la load and
assign karnya sathi register and class.for name use hote

How it Works:

1. When a Java application requests a connection, the DriverManager searches for an appropriate
driver.
2. It matches the database URL with the drivers available.
3. The selected driver handles the communication.

Connection Example:
Connection con = DriverManager.getConnection("jdbc:odbc:My_database", "", "");
In this example, the DriverManager.getConnection() method is used to connect to a database named
My_database.
2. Connection Interface
 Purpose:
Represents a session(line) with the database. All communication with the database happens
through this connection.
 Key Methods:
o Statement createStatement(): Creates a Statement object to execute SQL queries.
o PreparedStatement prepareStatement(String sql): Creates a PreparedStatement object for
parameterized queries.

o Example: SELECT * FROM customers WHERE id = ? (yahan ? ek dynamic parameter hai).

o void close(): Closes the connection to release resources.


o void commit(): Commits a transaction.
o void rollback(): Rolls back a transaction.
Exception Handling:
 ClassNotFoundException: Thrown if the specified driver class isn’t found.
 SQLException: Thrown if there’s a database access error.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

class PrepareStatementExample {
public static void main(String[] args) {
try {
// Step 1: Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish a connection to the database
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"password");

// Step 3: Prepare an SQL query with placeholders


String sql = "INSERT INTO students (id, name, age) VALUES (?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql);

// Step 4: Set the values for the placeholders


pstmt.setInt(1, 101); // Set value for the first placeholder
pstmt.setString(2, "John"); // Set value for the second placeholder
pstmt.setInt(3, 20); // Set value for the third placeholder

// Step 5: Execute the query


int rowsInserted = pstmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted successfully!");

// Close the connection


con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

3. Statement Interface
 Purpose:
Executes SQL queries that do not require parameters.
 Statement Create Kaise Hota Hai?

Statement stat = con.createStatement();

 Yahan con ek Connection object hai jo database se connected hai.


 createStatement() method Statement object banata hai.
Statement ke Execution Methods
1. execute()
o Ye kisi bhi SQL statement ko execute kar sakta hai (SELECT, INSERT, UPDATE, DELETE).
o Agar query result set return kare (jaise SELECT query), to ye true return karega.

boolean result = stat.execute("SELECT * FROM students");

2. executeUpdate()
o INSERT, UPDATE, DELETE queries ke liye use hota hai.
o Ye number of rows return karta hai jo query se affected hoti hain.
int rows = stat.executeUpdate("UPDATE students SET age=20 WHERE id=1");

3. executeQuery()
o SELECT queries ke liye specific method hai.
o ResultSet return karta hai jo data contain karta hai.

ResultSet rs = stat.executeQuery("SELECT * FROM students");

stat.close();

 Ye resources ko free karta hai jo database ke saath connected hain.

Types of Statements

1. PreparedStatement
o Precompiled SQL query ke liye use hoti hai.
o Jahan bar-bar values change hoti hain, ye efficient hota hai.
o Example:

PreparedStatement pstmt = con.prepareStatement("INSERT INTO students VALUES(?, ?)");


pstmt.setInt(1, rollNumber);
pstmt.setString(2, name);
pstmt.executeUpdate();
? placeholders hain, jisme tum baad mein values doge.

Benefits:
o
SQL Injection safe hai.

Query bar-bar compile nahi hoti, performance better hoti hai.

2. CallableStatement
o Stored procedures ko call karne ke liye use hota hai.
o Stored procedures database mein pre-defined SQL code blocks hote hain.
o Example:

CallableStatement callable = con.prepareCall("{call procedureName(?, ?)}");


callable.setInt(1, value);
callable.registerOutParameter(2, Types.INTEGER);
callable.execute();

“Without stored procedure: Har baar pizza ke liye ingredients aur process likho.
With stored procedure: Recipe save hai, sirf naam bolke pizza ready ho jaata hai.
CallableStatement is the "chef" jo recipe ko call karta hai aur result deta hai.”

5.4.5 ResultSet Interface

ResultSet Interface ka use SELECT queries ke result ko fetch karne ke liye hota hai.
ResultSet Create Kaise Hota Hai?

java
Copy code
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM students");

 executeQuery() method result ko ResultSet object mein store karta hai.

ResultSet Mein Navigate Karna

1. next(): Pointer ko next row pe move karta hai.

java
Copy code
while (rs.next()) {
System.out.println(rs.getString("name"));
}

2. first(): First row pe move karta hai.


3. last(): Last row pe move karta hai.
4. previous(): Pichle row pe move karta hai.
5. getRow(): Current row ka number batata hai.

ResultSet Se Data Read Karna

1. getInt(index): Index se integer value fetch karta hai.


2. getString(columnName): Column name se string value fetch karta hai.

int id = rs.getInt("id");
String name = rs.getString("name");

ResultSet Mein Data Update Karna

1. updateString(int index, String value): Index par value update karta hai.
2. updateRow(): Current row update karta hai.
3. deleteRow(): Current row delete karta hai.
4. insertRow(): Nayi row insert karta hai.

5. ResultSet Interface
Types of ResultSet:
1. Forward-only: Cursor moves in a forward direction only.
2. Scrollable: Cursor can move both forward and backward.
3. Updatable: Allows modification of rows in the result set.

Key Points to Remember for MCQs


 DriverManager is responsible for managing database drivers and establishing connections.
 Connection is the starting point for executing queries.
 Statement is simple but does not support parameters.
 PreparedStatement is used for parameterized queries and prevents SQL injection.
 ResultSet is used to fetch query results.

Important points for mcq which is not in the syllabus :

3. What is, in terms of JDBC, a data source?

a. A datasource is the basic service for managing a set of JDBC drivers


b. A data source is the java representation of a physical data source
c. A datasource is a registry point for JNDI-services
d. A data source is a factory of connections to a physical data source

Data source :
DataSource is an alternative to using the DriverManager for establishing database connections.
It provides a factory for connections to a physical database.
 DataSources are often registered with a Java Naming and Directory Interface (JNDI) for easier
lookups in applications.

 JNDI ke sath DataSource ko register karna possible hai, par ye DataSource ka main purpose nahi
hai.
DataSource ka primary kaam hai database ke liye connection provide karna (as a connection
factory). JNDI bas ek tarika hai DataSource ko manage karne aur application me access karne ka.

Toh, sirf JNDI services se link karna DataSource ka main role nahi hota! 😊
Very important :
Correct answer: c. Both a & b
Explanation:
1. registerDriver() method:
 This method explicitly registers a driver with the DriverManager.
 Example:

.
Class.forName():
 This method dynamically loads the driver class into memory.
 When the driver class is loaded, it automatically registers itself with the DriverManager.
 Example:

Why both are needed?


 You can use either method, but both are valid ways to load a driver. Therefore, the correct answer is
c. Both a & b.
 getConnection() method is used after the driver is loaded to establish a connection, so it’s not for
loading the driver.

 What happens if you call deleteRow() on a ResultSet Object?

o The row you are positioned on is deleted from the ResultSet, but not from
the database
o The row you are positioned on is deleted from the ResultSet and from the
database
o The result depends on whether the property synchronize with
DataSource is set to true or false
o You will get a compile error
 When the message “No suitable driver” occurs?

o When the driver is not registered by class.forname() method


o When the user name, password and the database does not match
o When the JDBC database URL passed is not constructed properly
o When the type 4 driver is used
548. What should be the correct order to close the database resource?What should be the correct order
to close the database resource?
1. Connection, Statements, and then ResultSet
2. ResultSet, Connection, and then Statements
3. Statements, ResultSet, and then Connection
4. ResultSet, Statements, and then Connection
Note it

 DBC tracing is a feature designed for debugging. It provides detailed logs about what is happening
internally during JDBC operations, such as driver loading, connection management, and SQL execution. This
is the correct enabled feature for debugging.
1. jdbc.odbc.JdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();

dentify the DSN in the following statement: DriverManager.getConnection("jdbc:odbc:oradsn", "scott",


"tiger") 1. jdbc 2. odbc 3. scott 4.oradsn

In the statement:
java
Copy code
DriverManager.getConnection("jdbc:odbc:oradsn", "scott", "tiger");
 jdbc:odbc: is the JDBC-ODBC bridge protocol prefix, indicating the use of an ODBC (Open Database
Connectivity) connection.
 oradsn is the DSN (Data Source Name) that specifies the name of the ODBC data source. It is
essentially a reference to a pre-configured data source or ODBC connection setup (which might be
configured in the ODBC Data Source Administrator on the operating system).
So, in this case, oradsn is the DSN used to identify the specific database connection.
Breakdown of Other Options:
1. jdbc: This is the JDBC prefix that indicates the use of JDBC (not the DSN).
2. odbc: This is the ODBC protocol part of the JDBC-ODBC bridge URL, not the DSN.
3. scott: This is the username provided to the connection, not the DSN.
//

getConnection("jdbc:thin@localhost:1521:oracle", "scott", "tiger");

4. reateStatement() method without any parameter is used to create a statement with

a forward only and read only ResultSet


2. jdbc.odbc.JdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();

You might also like