interacting with database self notes
interacting with database self notes
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.
- 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.
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.
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.
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");
3. Statement Interface
Purpose:
Executes SQL queries that do not require parameters.
Statement Create Kaise Hota Hai?
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.
stat.close();
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:
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:
“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.”
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");
java
Copy code
while (rs.next()) {
System.out.println(rs.getString("name"));
}
int id = rs.getInt("id");
String name = rs.getString("name");
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.
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:
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?
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();
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.
//