0% found this document useful (0 votes)
138 views18 pages

JDBC & Odbc

ODBC is an SQL-based API created by Microsoft that allows Windows applications to access databases via SQL. It consists of four main components - the application, driver manager, driver, and data source. JDBC is the Java equivalent that allows Java applications to connect and execute queries on databases. There are four main types of JDBC drivers - JDBC-ODBC bridge driver, native driver, network protocol driver, and thin driver. The main CRUD operations in JDBC are creating, reading, updating, and deleting records using INSERT, SELECT, UPDATE, and DELETE SQL statements. PreparedStatements are pre-compiled SQL statements that improve performance and security over regular Statements.

Uploaded by

Ayush Prince
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)
138 views18 pages

JDBC & Odbc

ODBC is an SQL-based API created by Microsoft that allows Windows applications to access databases via SQL. It consists of four main components - the application, driver manager, driver, and data source. JDBC is the Java equivalent that allows Java applications to connect and execute queries on databases. There are four main types of JDBC drivers - JDBC-ODBC bridge driver, native driver, network protocol driver, and thin driver. The main CRUD operations in JDBC are creating, reading, updating, and deleting records using INSERT, SELECT, UPDATE, and DELETE SQL statements. PreparedStatements are pre-compiled SQL statements that improve performance and security over regular Statements.

Uploaded by

Ayush Prince
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/ 18

ODBC

ODBC is an SQL-based Application Programming Interface


(API) created by Microsoft that is used by Windows software
applications to access databases via SQL.

How ODBC works


ODBC consists of four components, working together to enable
functions. ODBC allows programs to use SQL requests that
access databases without knowing the proprietary interfaces to
the databases. ODBC handles the SQL request and converts it
into a request each database system understands.
• Application: Processes and calls the ODBC functions
and submits the SQL statements;
• Driver manager: Loads drivers for each application;

• Driver: Handles ODBC function calls, and then submits


each SQL request to a data source; and

• Data source: The data being accessed and its database


management system (DBMS) OS.
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java
API to connect and execute the query with the database. It is a
part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of
JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to
connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function
calls. This is now discouraged because of thin driver.

o
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is
converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client
machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into native
calls of the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on each client
machine.
o The Vendor client library needs to be installed on client
machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application
server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is fully written in java.
Advantage:
o No client-side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle
tier.
o Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in
the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known
as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.

Difference between ODBC & JDBC

ODBC JDBC
ODBC Stands for Open Database JDBC Stands for java
Connectivity. database connectivity.
Introduced by SUN Micro
Introduced by Microsoft in 1992. Systems in 1997.
We can use ODBC for any language We can use JDBC only for
like C,C++,Java etc. Java languages.
We can choose ODBC only windows We can Use JDBC in any
platform. platform.
Mostly ODBC Driver developed in native JDBC Stands for java
languages like C,C++. database connectivity.
For Java applications it is not For Java application it is
recommended to use ODBC because highly recommended to use
performance will be down due to internal JDBC because there are no
conversion and applications will become performance & platform
platform Dependent. dependent problem.
ODBC is procedural. JDBC is object oriented.

CRUD OPERATION
Creating, reading, updating, and deleting data in a database is a common
task in many applications, and JDBC (Java Database Connectivity) is a Java
API that allows you to connect to a database and perform these operations.
1. Connect to the database
The first step is to establish a connection to the database. You can do this by loading the JDBC
driver and creating a connection object.

try {

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

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/mydb", "username",

"password");

System.out.println("Connection established.");

catch (Exception e) {

e.printStackTrace();
}
2. Create a new record
Once you have a connection to the database, you can use the connection
object to create a new record in the database. To do this, you will need to use
an SQL INSERT statement and execute it using the connection object.

try {
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES
(?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.setInt(3, 123);
statement.executeUpdate();
System.out.println("Record created.");
} catch (SQLException e) {
e.printStackTrace();
}
3. Read a record
To read a record from the database, you will need to use an SQL SELECT
statement and execute it using the connection object. The result of the query
will be a ResultSet object that you can use to access the data in the record.

try {
String sql = "SELECT column1, column2, column3 FROM table_name WHERE
id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
ResultSet result = statement.executeQuery();
if (result.next()) {
String column1 = result.getString("column1");
String column2 = result.getString("column2");
int column3 = result.getInt("column3");
System.out.println("Column 1: " + column1);
System.out.println("Column 2: " + column2);
System.out.println("Column 3: " + column3);
}
} catch (SQLException e) {
e.printStackTrace();
}
4. Update a record
To update a record in the database, you will need to use an SQL UPDATE
statement and execute it using the connection object.

try {
String sql = "UPDATE table_name SET column1 = ?, column2 = ?, column3 = ?
WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "new_value1");
statement.setString(2, "new_value2");
statement.setInt(3, 456);
statement.setInt(4, 1);
statement.executeUpdate();
System.out.println("Record updated.");
} catch (SQLException e) {
e.printStackTrace();
}
5. Delete a record
To delete a record from the database, you will need to use an SQL DELETE
statement and execute it using the connection object.

try {
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
statement.executeUpdate();
System.out.println("Record deleted.");
} catch (SQLException e) {
e.printStackTrace();
}

Prepared Statement
A PreparedStatement is a pre-compiled SQL statement. It is a subinterface
of Statement. Prepared Statement objects have some useful additional
features than Statement objects. Instead of hard coding queries,
PreparedStatement object provides a feature to execute a parameterized
query.

Advantages of PreparedStatement

• When PreparedStatement is created, the SQL query is passed as a


parameter. This Prepared Statement contains a pre-compiled SQL
query, so when the PreparedStatement is executed, DBMS can just run
the query instead of first compiling it.
• We can use the same Prepared Statement and supply with different
parameters at the time of execution.

• An important advantage of Prepared Statements is that they prevent


SQL injection attacks.

Steps to use Prepared Statement

1. Create Connection to Database


• Connection myCon = DriverManager.getConnection(path,username,password);
2. Prepare Statement
PreparedStatement myStmt;
myStmt = myCon.prepareStatement(select * from students where age> ? and name = ?);
3. Set parameter values for type and position

myStmt.setInt(1,10);
myStmt.setString(2,"Java");
4. Execute the Query
ResultSet myRs= myStmt.executeQuery();

Statement
The statement interface is used to create SQL basic statements in Java it
provides methods to execute queries with the database. There are different
types of statements that are used in JDBC as follows:
• Create Statement
• Prepared Statement
• Callable Statement

1. Create a Statement: From the connection interface, you can create the
object for this interface. It is generally used for general–purpose access to
databases and is useful while using static SQL statements at runtime.
Syntax:
Statement statement = connection.createStatement();
Implementation: Once the Statement object is created, there are three ways to
execute it.
• boolean execute(String SQL): If the ResultSet object is retrieved,
then it returns true else false is returned. Is used to execute SQL
DDL statements or for dynamic SQL.
• int executeUpdate(String SQL): Returns number of rows that are
affected by the execution of the statement, used when you need a
number for INSERT, DELETE or UPDATE statements.
• ResultSet executeQuery(String SQL): Returns a ResultSet object.
Used similarly as SELECT is used in SQL.

// Java Program illustrating Create Statement in JDBC

// Importing Database(SQL) classes


import java.sql.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Try block to check if any exceptions occur


try {

// Step 2: Loading and registering drivers

// Loading driver using forName() method


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

// Registering driver using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 3: Create a statement


Statement statement = con.createStatement();
String sql = "select * from people";

// Step 4: Execute the query


ResultSet result = statement.executeQuery(sql);

// Step 5: Process the results

// Condition check using hasNext() method which


// holds true till there is single element
// remaining in List
while (result.next()) {

// Print name an age


System.out.println(
"Name: " + result.getString("name"));
System.out.println(
"Age:" + result.getString("age"));
}
}

// Catching database exceptions if any


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catching generic ClassNotFoundException if any


catch (ClassNotFoundException e) {

// Print and display the line number


// where exception occurred
e.printStackTrace();
}
}
}

ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.

But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface


1) public boolean next(): is used to move the cursor to the one row next
from the current position.

2) public boolean previous(): is used to move the cursor to the one row previous
from the current position.

3) public boolean first(): is used to move the cursor to the first row in result
set object.

4) public boolean last(): is used to move the cursor to the last row in result
set object.

5) public boolean is used to move the cursor to the specified row


absolute(int row): number in the ResultSet object.

6) public boolean relative(int is used to move the cursor to the relative row
row): number in the ResultSet object, it may be positive
or negative.

7) public int getInt(int is used to return the data of specified column


columnIndex): index of the current row as int.

8) public int getInt(String is used to return the data of specified column


columnName): name of the current row as int.

9) public String getString(int is used to return the data of specified column


columnIndex): index of the current row as String.

10) public String is used to return the data of specified column


getString(String name of the current row as String.
columnName):

Example of Scrollable ResultSet


Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","sy
stem","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSe
t.CONCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}

ResultSetMetaData Interface
The metadata means data about data i.e., we can get further information from the data.

If you have to get metadata of a table like total number of columns, column name,
column type etc., ResultSetMetaData interface is useful because it provides methods to
get metadata from the ResultSet object.

Commonly used methods of ResultSetMetaData interface

Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in


the ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.

public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.

public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.

Example of ResultSetMetaData interface :


1. import java.sql.*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. PreparedStatement ps=con.prepareStatement("select * from emp");
10. ResultSet rs=ps.executeQuery();
11. ResultSetMetaData rsmd=rs.getMetaData();
12.
13. System.out.println("Total columns: "+rsmd.getColumnCount());
14. System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
15. System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeNa
me(1));
16.
17. con.close();
18. } catch(Exception e){ System.out.println(e);}
19. }
20. }
21. 2
22. Column Name of 1st column: ID
23. Column Type Name of 1st column: NUMBER

Output: Total columns: 2

Column Name of 1st column: ID

Column Type Name of 1st column: NUMBER

You might also like