java_unit3
java_unit3
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.
What is API
API (Application programming interface) is a document that contains 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
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
Advantages:
o easy to use.
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.
Advan
tage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
Disadvantages:
o Network support is required on client machine.
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.
Disadvantage:
o Drivers depends on the Database.
o Creating connection
o Creating statement
o Executing queries
o Closing connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Class.forName("oracle.jdbc.driver.OracleDriver");
4. Password: Password is given by the user at the time of installing the oracle
database.
Let's first create a table in oracle database.
1. create table emp(id number(10),name varchar2(40),age number(3));
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.
DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and
the appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Connection interface
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of
Connection can be used to get the object of Statement and DatabaseMetaData. The
Connection interface provide many methods for transaction management like commit(),
rollback() etc.
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources
immediately.
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.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
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","syste
m","oracle");
Statement stmt=con.createStatement();
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
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:
2) public boolean previous(): is used to move the cursor to the one row previous from the current p
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 number in the ResultS
absolute(int row):
6) public boolean relative(int is used to move the cursor to the relative row number in the Result
row): may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the current row
columnIndex):
8) public int getInt(String is used to return the data of specified column name of the current row
columnName):
9) public String getString(int is used to return the data of specified column index of the current row
columnIndex):
10) public String is used to return the data of specified column name of the current row
getString(String
columnName):
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)
public void setString(int paramIndex, sets the String value to the given parameter index.
String value)
public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)
public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
int i=stmt.executeUpdate();
System.out.println(i+" records updated");
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
Example of PreparedStatement interface that retrieve the records
of a table
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.
Java socket programming provides facility to share data between different computing
devices.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.
6) Socket
A socket is an endpoint between two way communication.
2. Port number.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:
1. http://www.javatpoint.com/java-tutorial
4. File Name or directory name: In this case, index.jsp is the file name.
Method Description
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}