Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
(JDBC)
Contents
• Data Base
• Database Schema
• A Brief Overview Of The JDBC Process
• JDBC Driver Types
• JDBC Packages
• Database Connection
• Creating, Inserting, Updating And Deleting Data In Database
Tables
• Result Set
Data Base & Database Schema
• Database is a large collection of related data that can be stored
generally describes activities of an organization.
• A database management system (DBMS) is a collection of
programs (software) for defining, creating, manipulating and
maintaining a database.
• Database Schema refers to the overall structure of a database.
• The description of a database is called the database schema,
which is specified during database design and is not expected to
change frequently
Cont …
STUDENT
• TEACHER
> Data access portions had to be rewritten with changes in the application.
> Application developers were stuck with a particular database product for a given
application
ODBC(Open Database Connectivity)
> A standard or open application programming interface (API) for accessing a database
> Allows programs to use SQL requests that will access databases without knowledge of
the proprietary interfaces to the databases
ODBC Requirements
An ODBC software for a particular OS.
A separate module or driver for each database to be accessed
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).
Why Java ???
> Write once, run anywhere
• The JDBC type 2 driver uses the libraries of the database which is available
at client side
• The driver converts JDBC method calls into native calls of the database API
• so this driver is also known as a Native-API driver
• These drivers are typically provided by the database vendors.
• The vendor-specific driver must be installed on each client machine.
• If we change the Database, we have to change the native API, as it is
specific to a database
Type 2 Driver : Native-API Driver (Partly Java driver).
Advantage:
•performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
•The Native driver needs to be installed on the each client machine.
•The Vendor client library needs to be installed on client machine.
Type 3 Driver : Network-Protocol Driver(Pure Java driver for database
Middleware).
Cont…
java.sql package
•The first package is called java.sql and contains core JDBC interfaces of
the JDBC API.
•These include the JDBC interfaces that provide the basics for connecting
to the DBMS and interacting with data stored in the DBMS
•This package include classes and interface to perform almost all JDBC
operation such as creating and executing SQL Queries.
classes and interface of java.sql package
classes/interface Description
java.sql.Connection creates a connection with specific database
java.sql.CallableStatement Execute stored procedures
•The JDBC driver must be loaded before the Java application can
connect to the DBMS.
•The Class.forName() method is used to load the JDBC driver
•Here forName() is a method of class Class.
•The driver is loaded by calling the Class.forName() method and
passing it the name of the driver
Class.forName("com.mysql.jdbc.Driver");
2. Creating a Connection to DataBase
•Once the driver is loaded, getConnection() method of DriverManager Class is
used to create a connection with the database.
•The Java application must connect to the DBMS using the
DriverManager.getConnection() method
Syntax:
getConnection(String url, String username, String password)
•url is the location of database.
• The DriverManager.getConnection() returns a Connection interface that is used
throughout the process to reference the database.
Example:
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/databasename","root","roo
t");
3. Creating a statement object
•The next step after the JDBC driver is loaded and a connection is
successfully made with a particular database is to send an SQL query to the
DBMS for processing.
•The statement object is responsible to execute queries with the database.
•createStatement() method of Connection object is used create a
Statement object.
Example:
Statement stmt=con.createStatement();
4. Executing a SQL statement
•The methods of Statement object is used to execute a query and return a
ResultSet object that contains the response from the DBMS.
Methods statement object:
executeQuery() is used for SELECT statement.
executeUpdate() is used for create, alter or drop table.
execute() is used when multiple results may be returned
Example:
String query="create table employee1(empid varchar(20),empname
varchar(30),empsal varchar(20))";
stmt.executeUpdate(query);
5. Closing the connection
•The close()method of Connection interface is used to close the
connection.
Con.close()
Example
import java.sql.*;
class create1
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="create table employee1(empid varchar(20),empname varchar(30),empsal
varchar(20))";
stmt.executeUpdate(query);
con.close();
}
}
Database Connection
•A Java application does not directly connect to a DBMS.
• Instead, the Java application connects with the JDBC driver that
is associated with the DBMS.
•However, before this connection is made, the JDBC driver must
be loaded and registered with the DriverManager.
•The purpose of loading and registering the JDBC driver is to bring
the JDBC driver into the Java Virtual Machine (JVM).
•The Class.forName() is used to load the JDBC driver.
•The Class.forName() throws a ClassNotFoundException if an error
occurs when loading the JDBC driver.
Cont …
•The connection to the database is established by using one of
three getConnection() methods of the DriverManager object.
•The getConnection() method requests access to the database
from the DBMS.
•It is up to the DBMS to grant or reject access.
•A Connection object is returned by the getConnection() method
if access is granted, otherwise the getConnection() method throws
an SQLException.
Cont …
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Example:
class create1
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/IIICSE","root","root");
}
Creating Table
import java.sql.*;
class create
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="create table employee(empid varchar(20) primary key,empname
varchar(30),empsal varchar(20))";
stmt.executeUpdate(query);
con.close();
}
}
Inserting data into Table
import java.sql.*;
class insertrow
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="insert into employee values(697,'ramireddy',59000)";
stmt.executeUpdate(query);
System.out.println("values inserted");
con.close();
}
}
Droping Tables
import java.sql.*;
class drop
{
public static void main(String [] args)throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="drop table student";
stmt.execute(query);
System.out.println("table is dropped");
con.close();
}
}
Updating Tables
import java.sql.*;
class update
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="update employee set esal=300000 where eid=1";
stmt.executeUpdate(query);
System.out.println("updated");
con.close();
}
}
Deleting data from tables
import java.sql.*;
class delete
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="delete from employee where eid=697";
stmt.executeUpdate(query);
System.out.println("deleted");
con.close();
}
}
ResultSet
•A ResultSet is a Java object that contains the results of an SQL query.
• In other words, it contains the rows that satisfy the conditions of the
query
•The executeQuery() method is used to send the query to the DBMS for
processing and returns a ResultSet object that contains data requested by
the query.
•The ResultSet object contains methods that are used to copy data from the
ResultSet into a Java variables for further processing.
• Data in a ResultSet object is logically organized into a virtual table
consisting of rows and columns.
•In addition to data, the ResultSet object also contains metadata, such as
column names, column size and column data type.
ResultSet
•The ResultSet uses a virtual cursor to point to a row of the virtual
table.
•The virtual cursor is positioned above the first row of data when
the ResultSet is returned by the executeQuery() method.
•The virtual cursor moved to the next row using the next()
method.
• next() method returns a boolean true if the row contains data,
otherwise a boolean false is returned, indicating that no more
rows exist in the ResultSet.
ResultSet
•Once the virtual cursor points to a row, the getXXX() method is
used to copy data from the row to a variable.
•For example, the getString() method is used to copy String data
from a column of the ResultSet.
• The getXXX() method requires one parameter, which is an
integer that represents the number of the column that contains
the data.
•For example, getString(1) copies the data from the first column
of the ResultSet.
Scrollable ResultSet
•Until the release of JDBC 2.1 API, the virtual cursor could only be moved
down the ResultSet object.
•But today the virtual cursor can be moved backwards or even positioned
at a specific row.
•The first() method moves the virtual cursor to the first row in the
ResultSet.
•The last() method positions the virtual cursor at the last row in the
ResultSet.
•The previous() method moves the virtual cursor to the previous row.
•The absolute() method positions the virtual cursor at the row number
specified by the integer passed as a parameter to the absolute() method.
•The getRow() method returns an integer that represents the number of
the current row in the ResultSet.
Scrollable ResultSet
•The Statement object that is created using the createStatement() of the
Connection object must be set up to handle a scrollable ResultSet by passing
the createStatement() method one of three constants.
• These constants are TYPE_FORWARD_ONLY,TYPE_SCROLL_INSENSITIVE,
and TYPE_SCROLL_SENSITIVE.
•The TYPE_FORWARD_ONLY constant restricts the virtual cursor to
downward movement.
• TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE constants
permit the virtual cursor to move in both directions.
Selecting data from tables
import java.sql.*;
class selectall
{
public static void main(String rags[])throws SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from employee");
while(rs.next())
{
System.out.println(rs.getInt(1) +" "+rs.getString(2)+" "+rs.getInt(3));
}
con.close();
}}
Example on Scrollable Result Set
import java.sql.*;
class select
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from employee");
rs.absolute(2);
System.out.println(rs.getString(1) +" "+rs.getString(2)+" "+rs.getInt(3));
con.close();
}
}
Statement Objects
The statement object is responsible to execute queries with the database.
There are 3 types of Statement Objects
1.Statement
2.Prepared Statement
3.Callable Statement
Any One of the three types of Statement objects is used to execute
the query.
Statement Object
•The Statement object is used whenever a Java application needs to
execute a query immediately without first having the query compiled.
•The statement object is responsible to execute queries with the database.
•createStatement() method of Connection object is used create a
Statement object.
Example:
Statement stmt=con.createStatement();
•The Statement interface provides three different methods for executing
SQL statements, executeQuery(), executeUpdate(), and execute().
•The method executeQuery(String sql) is designed for SELECT statements
that returns result set object .
Statement Object