[go: up one dir, main page]

0% found this document useful (0 votes)
10 views19 pages

Ava JDBC Tutorial

The document provides a comprehensive tutorial on Java Database Connectivity (JDBC), detailing its purpose, types of JDBC drivers, and how to connect Java applications to various databases like Oracle and MySQL. It outlines the steps for establishing a database connection, executing queries, and managing database operations using JDBC API. Additionally, it explains the advantages and disadvantages of different JDBC drivers and includes code examples for practical implementation.

Uploaded by

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

Ava JDBC Tutorial

The document provides a comprehensive tutorial on Java Database Connectivity (JDBC), detailing its purpose, types of JDBC drivers, and how to connect Java applications to various databases like Oracle and MySQL. It outlines the steps for establishing a database connection, executing queries, and managing database operations using JDBC API. Additionally, it explains the advantages and disadvantages of different JDBC drivers and includes code examples for practical implementation.

Uploaded by

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

ava JDBC Tutorial

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:

ADVERTISEMENT
ADVERTISEMENT

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational
database. By the help of JDBC API, we can save, update, delete and
fetch data from the database. It is like Open Database Connectivity
(ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st
September, 2017. It is based on the X/Open SQL Call Level Interface.
The java.sql package contains classes and interfaces for JDBC API.
A list of popular interfaces of JDBC API are given below:

Backward Skip 10sPlay VideoForward Skip 10s

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:

o DriverManager class
o Blob class
o Clob class
o Types class

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and
execute the query with the database. But, ODBC API uses ODBC
driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that
uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and
can perform the following activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

Do You Know
o How to connect Java application with Oracle and Mysql
database using JDBC?
o What is the difference between Statement and
PreparedStatement interface?
o How to print total numbers of tables and views of a database
using JDBC?
o How to store and retrieve images from Oracle database using
JDBC?
o How to store and retrieve files from Oracle database using
JDBC?

What is API
API (Application programming interface) is a document that contains
a description of all the features of a product or software. It
represents classes and interfaces that software programs can follow
to communicate with each other. An API can be created for
applications, libraries, operating systems, etc.

Topics in Java JDBC Tutorial


2) JDBC Drivers

In this JDBC tutorial, we will learn four types of JDBC drivers, their
advantages and disadvantages.

3) 5 Steps to connect to the Database

In this JDBC tutorial, we will see the five steps to connect to the
database in Java using JDBC.

4) Connectivity with Oracle using JDBC

In this JDBC tutorial, we will connect a simple Java program with the
Oracle database.

5) Connectivity with MySQL using JDBC

In this JDBC tutorial, we will connect a simple Java program with the
MySQL database.

6) Connectivity with Access without DSN

Let's connect java application with access database with and


without DSN.

7) DriverManager class

In this JDBC tutorial, we will learn what does the DriverManager


class and what are its methods.

8) Connection interface

In this JDBC tutorial, we will learn what is Connection interface and


what are its methods.
9) Statement interface

In this JDBC tutorial, we will learn what is Statement interface and


what are its methods.

10) ResultSet interface

In this JDBC tutorial, we will learn what is ResultSet interface and


what are its methods. Moreover, we will learn how we can make the
ResultSet scrollable.

11) PreparedStatement Interface

In this JDBC tutorial, we will learn what is benefit of


PreparedStatement over Statement interface. We will see examples
to insert, update or delete records using the PreparedStatement
interface.

12) ResultSetMetaData interface

In this JDBC tutorial, we will learn how we can get the metadata of a
table.

13) DatabaseMetaData interface

In this JDBC tutorial, we will learn how we can get the metadata of a
database.

14) Storing image in Oracle

Let's learn how to store image in the Oracle database using JDBC.

15) Retrieving image from Oracle

Let's see the simple example to retrieve image from the Oracle
database using JDBC.

16) Storing file in Oracle

Let's see the simple example to store file in the Oracle database
using JDBC.
17) Retrieving file from Oracle

Let's see the simple example to retrieve file from the Oracle
database using JDBC.

18) CallableStatement

Let's see the code to call stored procedures and functions using
CallableStatement.

19) Transaction Management using JDBC

Let's see the simple example to use transaction management using


JDBC.

20) Batch Statement using JDBC

DBC Driver
. JDBC Drivers
. JDBC-ODBC bridge driver
. Native-API driver
. Network Protocol driver
. Thin driver

JDBC Driver is a software component that enables java application to interact wit
drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDB
calls into the ODBC function calls. This is now discouraged because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of
your database instead of the JDBC-ODBC Bridge.

Advantages:
ADVERTISEMENT
ADVERTISEMENT

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 conve
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 the 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 protoc
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.

Let's see the code to execute batch of queries.

Java Database Connectivity with 5


Steps
. 5 Steps to connect to the database in java
. Register the driver class
. Create the connection object
. Create the Statement object
. Execute the query
. Close the connection object
There are 5 steps to connect any java application with the database using JDBC. The
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This me
class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFou


ndException

Note: Since JDBC 4.0, explicitly registering the driver is optional.


We just need to put vender's Jar in the classpath, and then JDBC
driver manager can detect and load the driver automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database
connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connectio

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLE


xception
2. 2) public static Connection getConnection(String url,String name,S
tring password)
3. throws SQLException

Example to establish connection with the


Oracle database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statemen
execute queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

Example to create the statement object


1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to th
of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");


2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically.
is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException

Example to close connection


ADVERTISEMENT
ADVERTISEMENT

1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources
statement to automatically close resources of type Connection,
ResultSet, and Statement.

Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5 following
10g as the database. So we need to know following information for the oracle datab
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.O
2. Connection URL: The connection URL for the oracle10G database is jdbc:or
is the API, oracle is the database, thin is the driver, localhost is the server na
use IP address, 1521 is the port number and XE is the Oracle service name.
tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the or

Create a Table

Before establishing connection, let's first create a table in oracle database. Following

1. create table emp(id number(10),name varchar2(40),age number(3))


;

Example to Connect Java Application with


Oracle database
In this example, we are connecting to an Oracle database and
getting data from emp table. Here, system and oracle are the
username and password of the Oracle database.

1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getStrin
g(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
download this example

The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file


is required to be loaded.

download the jar file ojdbc14.jar

Two ways to load the jar file:

1. paste the ojdbc14.jar file in jre/lib/ext folder


2. set classpath

1) paste the ojdbc14.jar file in JRE/lib/ext folder:


Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file h

2) set classpath:
There are two ways to set the classpath:
o temporary
o permanent

How to set the temporary classpath:


Firstly, search the ojdbc14.jar file then open command prompt and write:

1. C:>set classpath=c:\folder\ojdbc14.jar;.;

How to set the permanent classpath:


Go to environment variable then click on new tab. In variable name
write classpath and in variable value paste the path to ojdbc14.jar
by appending ojdbc14.jar;.; as C:\oraclexe\app\oracle\product\
10.2.0\server\jdbc\lib\ojdbc14.jar;.;

Java Database Connectivity with MySQL


To connect Java application with the MySQL database, we need to
follow 5 following steps.

In this example we are using MySql as the database. So we need to


know following informations for the mysql database:

1. Driver class: The driver class for the mysql database


is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API,
mysql is the database, localhost is the server name on which
mysql is running, we may also use IP address, 3306 is the port
number and sonoo is the database name. We may use any
database, in such case, we need to replace the sonoo with our
database name.
3. Username: The default username for the mysql database
is root.
4. Password: It is the password given by the user at the time of
installing the mysql database. In this example, we are going to
use root as the password.
Let's first create a table in the mysql database, but before creating
table, we need to create database first.

1. create database sonoo;


2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with


mysql database
In this example, sonoo is the database name, root is the username
and password both.

1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getStrin
g(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }
download this example

The above example will fetch all the records of emp table.

To connect java application with the mysql


database, mysqlconnector.jar file is required to be loaded.
download the jar file mysql-connector.jar

Two ways to load the jar file:

1. Paste the mysqlconnector.jar file in jre/lib/ext folder


2. Set classpath

1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:


Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file he

2) Set classpath:
There are two ways to set the classpath:
o temporary
o permanent

How to set the temporary classpath


open command prompt and write:

1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name
write classpath and in variable value paste the path to the
mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\
folder\mysql-connector-java-5.0.8-bin.jar;.;

Connectivity with Access without DSN


There are two ways to connect java application with the access
database.

1. Without DSN (Data Source Name)


2. With DSN

Java is mostly used with Oracle, mysql, or DB2 database. So you can
learn this topic only for knowledge.
Example to Connect Java Application with
access without DSN
In this example, we are going to connect the java program with the
access database. In such case, we have created the login table in
the access database. There is only one column in the table named
name. Let's get all the name of the login table.

1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String database="student.mdb";//Here database exists in the curr
ent directory
6.
7. String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
8. DBQ=" + database + ";DriverID=22;READONLY=true";

9.
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection c=DriverManager.getConnection(url);
12. Statement st=c.createStatement();
13. ResultSet rs=st.executeQuery("select * from login");
14.
15. while(rs.next()){
16. System.out.println(rs.getString(1));
17. }
18.
19. }catch(Exception ee){System.out.println(ee);}
20.
21. }}
download this example

Example to Connect Java Application with


access with DSN
Connectivity with type1 driver is not considered good. To connect
java application with type1 driver, create DSN first, here we are
assuming your dsn name is mydsn.

1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String url="jdbc:odbc:mydsn";
6. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
7. Connection c=DriverManager.getConnection(url);
8. Statement st=c.createStatement();
9. ResultSet rs=st.executeQuery("select * from login");
10.
11. while(rs.next()){
12. System.out.println(rs.getString(1));
13. }
14.
15. }catch(Exception ee){System.out.println(ee);}
16.
17. }}

You might also like