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

jdbc

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, architecture, and the necessary prerequisites for using it. It explains how JDBC enables Java applications to connect to various databases, execute SQL commands, and manage data records. Additionally, it covers the use of Statement and PreparedStatement interfaces for executing SQL queries and handling result sets in Java applications.

Uploaded by

Male Nephlen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

jdbc

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, architecture, and the necessary prerequisites for using it. It explains how JDBC enables Java applications to connect to various databases, execute SQL commands, and manage data records. Additionally, it covers the use of Statement and PreparedStatement interfaces for executing SQL queries and handling result sets in Java applications.

Uploaded by

Male Nephlen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Prerequisites

Student must have understanding about class and interfaces concept.

Any Database Software(MySQL, oracle) was installed on your machine.

Knowledge about DBMS Commands like DDL, DML etc.

What Is Java JDBC?


JDBC is an abbreviation for the term Java Database Connection. JDBC is a API, also
known as an application programming interface that establishes a connection between
a standard database and Java application that intends to use that database.

Data is the new fuel that runs the current IT industry, and the data processing
applications utilize this data to extract the necessary information. But, the real question
is, how do we establish a connection between the data storage unit and the data
processing application?

Now that we know the definition of JDBC, let us understand why and where we need it.

Need for Java JDBC


JDBC is used for multiple applications to connect to various types of data storage units
that are both standard and advanced. We need JDBC for the following purposes.

• For establishing stable database connectivity with the application API.

• To execute SQL(Structured Query Language) queries and DDL/DML commands.

• For viewing and modify data records in the data storage units.

So, these were the places and purposes for which we needed a JDBC connection. We
will learn the data types supported in SQL and their compatibility with Java over JDBC.
Data Types in Java JDBC
The data types for Java and the data storage unit (here, the SQL) will differ. Hence we
need a translator. The JDBC driver takes the responsibility to communicate the data
types from Java to SQL to eliminate the ambiguity.
Most frequently used Datatypes are mentioned below:

Java Data type SQL Data type

java.lang.string VARCHAR

boolean BIT

java.math.BigDecimal NUMERIC

int INTEGER

float REAL

float FLOAT

double DOUBLE
Java JDBC Architecture
The Java JDBC architecture consists of the following primary segments. They are:

• JDBC Application

• JDBC API

• JDBC Manager

• JDBC Drivers

• Data Storage Units


JDBC Application
The JDBC application is in the topmost position of the JDBC architecture. JDBC
application is the data processing application that intends to access the data from the
different data storage units.

JDBC API
The JDBC API plays a significant role in the JDBC architecture. The JDBC API ensures
that a stable connection is established between the data storage unit and the JDBC
application.

JDBC Manager
The JDBC manager takes care of selecting the appropriate driver manager to ensure
that the driver software chosen supports the data storage unit's requirements to offer
an uninterrupted connection.

JDBC Drivers
The JDBC driver is the crucial unit in the JDBC architecture. JDBC driver is the first layer
of JDBC architecture that has direct contact with the data storage units.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
o Register the Driver class(Optional)
o Create connection
o Create statement
o Execute queries
o Close connection
import java.sql.*;

public class GFG {


public static void main(String arg[])
{
Connection connection = null;
try {
// below two lines are used for connectivity.
Class.forName("com.mysql.cj.jdbc.Driver");

connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"mydbuser", "mydbuser");

// mydb is database
// mydbuser is name of database
// mydbuser is password of database

Statement statement;
statement = connection.createStatement();
ResultSet resultSet;
resultSet = statement.executeQuery(
"select * from designation");
int code;
String title;
while (resultSet.next()) {
code = resultSet.getInt("code");
title = resultSet.getString("title").trim();
System.out.println("Code : " + code
+ " Title : " + title);
}
resultSet.close();
statement.close();
connection.close();
}
catch (Exception exception) {
System.out.println(exception);
}
} // function ends
} // class ends
Statement Interface
Statement Use this for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. The Statement interface cannot accept
parameters.
Creating Statement Object Before you can use a Statement object to execute a SQL
statement, you need to create one using the Connection object's createStatement( )
method, as in the following example –

Statement stmt = null;


Try {
stmt = conn.createStatement( );
...
} catch (SQLException e) {
...
} finally {
...
}

Once you've created a Statement object, you can then use it to execute an SQL
statement with one of its three execute methods.

• boolean execute (String SQL):


• int executeUpdate (String SQL):
• ResultSet executeQuery (String SQL):
boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can
be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements
or when you need to use truly dynamic SQL.
int executeUpdate (String SQL): Returns the number of rows affected by the execution
of the SQL statement. Use this method to execute SQL statements for which you
expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE
statement.
ResultSet executeQuery (String SQL): Returns a ResultSet object. • Use this method
when you expect to get a result set, as you would with a SELECT statement.
Closing Statement Object
A simple call to the close() method will do the job. If you close the Connection object
first, it will close the Statement object as well. However, you should always explicitly
close the Statement object to ensure proper cleanup.

Statement stmt = null;


try {
stmt = conn.createStatement( );
...
} catch (SQLException e) {
...
} finally {
stmt.close();
}

Statement Interface Example:

1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","oracle");
6. Statement stmt=con.createStatement();
7.
8. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
9. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=100
00 where id=33");
10. int result=stmt.executeUpdate("delete from emp765 where id=33");
11. System.out.println(result+" records affected");
12. con.close();
13. }}
PreparedStatement Interface

• The PreparedStatement interface extends the Statement interface, which gives


you added functionality with a couple of advantages over a generic Statement
object.
• This statement gives you the flexibility of supplying arguments dynamically.
• Creating PreparedStatement Object.

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . . } catch (SQLException e) {
...
} finally {
...
}

All parameters in JDBC are represented by the ? symbol, which is known as the
parameter marker. You must supply values for every parameter before executing the
SQL statement.
The setType(position,value) methods bind values to the parameters, where XXX
represents the Java data type of the value you wish to bind to the input parameter. If
you forget to supply the values, you will receive an SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array
indices, which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can input the
parameters

Closing PreparedStatement Objects


A simple call to the close() method will do the job.
If you close the Connection object first, it will close the PreparedStatement object as
well.
However, you should always explicitly close the PreparedStatement object to ensure
proper cleanup.

PreparedStatement pstmt = null;


Try { String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
} catch (SQLException e) {
...
} finally {
pstmt.close();
}

PreparedStatement Interface Example:

import java.sql.*;

public class Demo {


Connection connection = null;
// Driver Code
public static void main(String[] args) throws Exception
{

// Register Driver Class (Optional)


Class.forName("com.mysql.cj.jdbc.Driver");

connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"mydbuser", "mydbuser");
// Query which needs parameters
String query
= "Select * from students where age> ? and name = ?";

// Prepare Statement
PreparedStatement myStmt
= con.prepareStatement(query);

// Set Parameters
myStmt.setInt(1, 20);
myStmt.setString(2, 'Prateek');

// Execute SQL query


ResultSet myRs = myStmt.executeQuery();

System.out.println('Age Name');

// Display function to show the Resultset


while (myRs.next()) {
String Name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(Name + " " + age);
}

// Close the connection


con.close();
}
}

ResultSet Interface
The SQL statements that read data from a database query, return the data in a result
set.
The SELECT statement is the standard way to select rows from a database and view
them in a result set. The java.sql.ResultSet interface represents the result set of a
database query.
A ResultSet object maintains a cursor that points to the current row in the result set.
The term "result set" refers to the row and column data contained in a ResultSet object.

A table of data representing a database result set, which is usually generated by


executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the
cursor is positioned before the first row. The next method moves the cursor to the next
row, and because it returns false when there are no more rows in the ResultSet object, it
can be used in a while loop to iterate through the result set.

A default ResultSet object is not updatable and has a cursor that moves forward only.

The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for
retrieving column values from the current row.

Values can be retrieved using either the index number of the column or the name of the
import java.sql.*;
column.
class ResultSetDemo{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","oracle");

// Query which needs parameters


String query
= "Select * from students where age> ?";

// Prepare Statement
PreparedStatement myStmt = con.prepareStatement(query);

// Set Parameters
myStmt.setInt(1, 20);

// Execute SQL query


ResultSet myRs = myStmt.executeQuery();

System.out.println(“Age “);

// Display function to show the Resultset


while (myRs.next()) {
int age = rs.getInt("age");
System.out.println(age);
}

// Close the connection


con.close();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy