Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Unit IV

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

BCA - JAVA

YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH


PRORAMMING

What is JDBC?
JDBC or Java Database Connectivity is a specification from Sun microsystems that provides a
standard abstraction (that is API or Protocol) for java applications to communicate with various
databases. It provides the language with java database connectivity standard. It is used to write
programs required to access databases. JDBC along with the database driver is capable of accessing
databases and spreadsheets.
JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −

 JDBC API: This provides the application-to-JDBC Manager connection.

 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with respect
to the JDBC drivers and the Java application −
1
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Common JDBC Components

The JDBC API provides the following interfaces and classes −

 Driver Manager: This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver using communication sub protocol.
The first driver that recognizes a certain sub protocol under JDBC will be used to establish a
database Connection.

 Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use Driver Manager objects, which
manages objects of this type. It also abstracts the details associated with working with Driver
objects.

 Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through
connection object only.

 Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.

 ResultSet: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.

 SQLException: This class handles any errors that occur in a database application.

JDBC Connectivity Model


2
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Types of JDBC Architecture


The JDBC architecture consists of two-tier and three-tier processing models to access a database. They
are as described below:
1. Two-tier model: A java application communicates directly to the data source. The
JDBC driver enables the communication between the application and the data source.
When a user sends a query to the data source, the answers for those queries are sent
back to the user in the form of results.The data source can be located on a different
machine on a network to which a user is connected. This is known as a client/server
configuration, where the user’s machine acts as a client and the machine having the
data source running acts as the server.
2. Three-tier model: In this, the user’s queries are sent to middle-tier services, from
which the commands are again sent to the data source. The results are sent back to the
middle tier, and from there to the user. This type of model is found very useful by
management information system directors.

Creating JDBC Application


There are following six steps involved in building a JDBC application −
 Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
 Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
 Open a connection: Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
 Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
 Extract data from result set: Requires that you use the appropriate method to retrieve
the data from the result set.
 Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
3
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Steps for connectivity between Java program and database

1. Loading the Driver


To begin with, you first need load the driver or register it before using it in the program . Registration
is to be done once in your program. You can register a driver in one of two ways mentioned below :

 Class.forName() : Here we load the driver’s class file into memory at the runtime. No need of
using new or creation of object .The following example uses Class.forName() to load the Oracle
driver –

Class.forName(“oracle.jdbc.driver.OracleDriver”);

 DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member


register. Here we call the constructor of the driver class at compile time. The following example
uses DriverManager.registerDriver()to register the Oracle driver –

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

2. Create the connections


After loading the driver, establish connections using:

Connection con = DriverManager.getConnection(url,user,password)

user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.
con: is a reference to Connection interface.
url : Uniform Resource Locator. It can be created as follows:

String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where oracle is the database used, thin is the driver used , @localhost is the IP Address where database
is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String
type and are to be declared by programmer before calling the function. Use of this can be referred from
final code.

3. Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL
4
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

commands and receive data from your database.


Use of JDBC Statement is as follows:
Statement st = con.createStatement();

Here, con is a reference to Connection interface used in previous step.

4. Execute the query


Now comes the most important part i.e executing the query. Query here is an SQL Query. Now we
know we can have multiple types of queries. Some of them are as follows:
 Query for updating / inserting table in a database.
 Query for retrieving data.
The executeQuery() method of Statement interface is used to execute queries of retrieving values from
the database. This method returns the object of ResultSet that can be used to get all the records of a
table.
The executeUpdate(sql query) method of Statement interface is used to execute queries of
updating/inserting .

Example:

int m = st.executeUpdate(sql);

if (m==1)

System.out.println("inserted successfully : "+sql);

else

System.out.println("insertion failed");

Here sql is sql query of the type String

5.Close the connections


So finally we have sent the data to the specified location and now we are at the verge of completion of
our task .
By closing connection, objects of Statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
Example :
con.close();
5
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Program:
Import java.sql.*;
import java.util.*;
class Main
{
public static void main(String a[])
{
//Creating the connection
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";

//Entering the data


Scanner k = new Scanner(System.in);
System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
int roll = k.nextInt();
System.out.println("enter class");
String cls = k.next();

//Inserting data using SQL query


String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
Connection con=null;
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

//Reference to connection interface


con = DriverManager.getConnection(url,user,pass);

Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
6
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

System.out.println("inserted successfully : "+sql);


else
System.out.println("insertion failed");
con.close();
}
catch(Exception ex)
{
System.err.println(ex);
}
}
}
Output –

STATEMENT INTERFACE

The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
7

4) public int[] executeBatch(): is used to execute batch of commands.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
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 absolute(int is used to move the cursor to the specified row number in
row): the ResultSet object.

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

7) public int getInt(int is used to return the data of specified column index of the
columnIndex): current row as int.

8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.

9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.

10) public String is used to return the data of specified column name of the
8
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

getString(String columnName): current row as String.

Example of Scrollable ResultSet

Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}

Java 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 column, 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


9
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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 index)throws it returns the column type name for the
SQLException specified index.

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

How to get the object of ResultSetMetaData:


The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:
1. public ResultSetMetaData getMetaData()throws SQLException

Example of ResultSetMetaData interface :


import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
10
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

JAVA APPLET

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including
the following −
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or
a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet

Four methods in the Applet class gives you the framework on which you build any serious applet −
 init − This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
 start − This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
11
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

 stop − This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy − This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
 paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet

Following is a simple applet named HelloWorldApplet.java −

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}

These import statements bring the classes into the scope of our applet class −

 java.applet.Applet
 java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
12
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

The Applet Class

Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods
that a derived Applet class may call to obtain information and services from the browser context.
These include methods that do the following −

 Get applet parameters


 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may −

 Request information about the author, version, and copyright of the applet
 Request a description of the parameters the applet recognizes
 Initialize the applet
 Destroy the applet
 Start the applet's execution
 Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those implementations
may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.

Invoking an Applet

An applet may be invoked by embedding directives in an HTML file and viewing the file through an
applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that
invokes the "Hello, World" applet −

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
13

message would appear here.


</applet>
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

<hr>
</html>

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and
height are also required to specify the initial size of the panel in which an applet runs. The applet
directive must be closed with an </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param> tags
between <applet> and </applet>. The browser ignores text and other tags between the applet tags.
Parameter in Applet

We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:

public String getParameter(String parameterName)

Example of using parameter in Applet:

import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
14
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Example of Graphics in applet:

import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
15

g.drawOval(70,200,30,30);
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
16
Page

You might also like