Java Unit IV
Java Unit IV
Java Unit IV
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 −
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
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.
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(new oracle.jdbc.driver.OracleDriver())
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:
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
Example:
int m = st.executeUpdate(sql);
if (m==1)
else
System.out.println("insertion failed");
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";
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
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
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
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");
con.close();
}}
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.
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.
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.
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.
import java.applet.*;
import java.awt.*;
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
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 −
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
<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:
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
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.
import java.applet.Applet;
import java.awt.*;
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