JDBC Ii
JDBC Ii
What is JDBC :-
JDBC stands for Java Database Connectivity.
Java Data Base Connectivity (JDBC) is a set of Java APIs used for
executing SQL statements. JDBC is much similar to Microsoft's Open
Database Connectivity (ODBC) interface to SQL (Structure Query
Language).
JDBC API is a set of interfaces and classes to be used for communicating
with a data base.
These interfaces and classes are found in the java.sql package.
JDBC or Java Database Connectivity is a Java API to connect and execute
the query with the database.
It is a specification from Sun microsystems that provides a standard
abstraction (API or Protocol) for java applications to communicate with
various databases.
JDBC is an API(Application programming interface) used in java
programming to interact with databases.
The classes and interfaces of JDBC allow the application to
send requests made by users to the specified database.
The JDBC API consists of a set of interfaces and classes written in the Java
programming language.
Using these standard interfaces and classes, programmers can write
applications that connect to databases, send queries written in structured
query language (SQL), and process the results.
1) Importing Packages
All the JDBC API classes and interfaces are stored in the package java.sql so it
is needed to import as-
import java.sql.*;
6) Processing Resultset-
The records returned by the resultSet object has been processed /navigating by
using different methods as-
while(rs.next())
{
System.out.pritln(rs.getInt(1) + " " + rs.getString(2));
}
Type 1 and type 2 rely heavily on additional software, (typically C/C++ DLLs)
installed on the client computer to provide database connectivity.
Type 3 and 4 are pure java implementations and require no additional software
to be installed on the client, except for the JDBC driver.
Disadvantages:
1. Performance is not good as it converts JDBC method calls into ODBC function
calls.
2. ODBC driver needs to be installed on the client machine.
3. Platform dependent.
Advantages:
1. It is faster than a JDBC-ODBC bridge driver.
Disadvantages:
1. Platform dependent.
2. The vendor client library needs to be installed on the client machine.
Advantages:
1. Platform independent.
2. Faster from Type1 and Type2 drivers.
3. It follows a three tier communication approach.
4. Multiple types of databases can be accessed at the same time.
Disadvantages:
1. It requires database-specific coding to be done in the middle tier.
Advantages:
1. Platform independent.
2. Faster than all other drivers.
3. They are completely written in java to achieve platform independence and
eliminate deployment administration issues.
Disadvantages:
1. It is database dependent.
2. Multiple types of databases can‟t be accessed at the same time.
Method Description
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
Example:
Study the following example code to understand the usage of try.... catch...
finally blocks.
//Display values
System.out.print("Roll No: " + rollno);
System.out.print(", Name: " + name);
System.out.print(", Mobile: " + mob);
}
1) DriverManager class :-
The DriverManager class is the component of JDBC API and also a member of
the java.sql package.
The DriverManager class acts as an interface between users and drivers.
It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver.
It contains all the appropriate methods to register and deregister the database
driver class and to create a connection between a Java application and the
database.
5) public static Driver getDriver(String url) : Those drivers that understand the
mentioned URL (present in the parameter of the method) are returned by this
method provided those drivers are mentioned in the list of registered drivers.
Program :-
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");
Program :-
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");
con.close();
}
}
3) Statement interface :-
The Statement interface provides methods to execute queries with the database.
The statement interface is used to create SQL basic statements in Java it provides
methods to execute queries with the database.
The object of this interface is used for firing a static SQL or PL/SQL queries and
returning the results it has produced.
The statement interface is a factory of ResultSet i.e. it provides factory method to get
the object of ResultSet.
import java.sql.*;
while (r.next())
{
System.out.println(r.getInt(1) + " " + r.getString(2));
}
con.close();
}
4) ResultSet interface:-
1) boolean next():- It is used to move the cursor to the one row next from the current
position.
2) boolean previous():- It is used to move the cursor to the one row previous from the
current position.
3) boolean first():- It is used to move the cursor to the first row in in the result set
object.
4) boolean last():- It is used to move the cursor to the last row in result set object.
5) boolean absolute (int row):- It is used to move the cursor to the specified row
number in the ResultSet object.
6) boolean relative (int row):- It is used to move the cursor to the relative row number
in the ResultSet object, it may be positive or negative.
7) int getInt (int columnIndex):- It is used to return the data of specified column index
of the current row as int.
8) int getInt (String columnName):- It is used to return the data of specified column
name of the current row as int.
10) String getString (String columnName):- It is used to return the data of specified
column of the current row as String.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");
con.close();
}
}
5) PreparedStatement interface :-
The PreparedStatement interface is a subinterface of Statement.
A PreparedStatement is a pre-compiled SQL statement.
It is used to execute parameterized query. The PreparedStatement interface
accepts input parameters at runtime.
Let's see the example of parameterized query.
String sql = "insert into emp values(?,?,?)";
We are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
This interface is used when we plan to use the same SQL statement many time.
Advantages of PreparedStatement
1) When PreparedStatement is created, the SQL query is passed as a parameter.
This Prepared Statement contains a pre-compiled SQL query, so when the
PreparedStatement is executed, DBMS can just run the query instead of first
compiling it.
2) We can use the same PreparedStatement and supply with different parameters
at the time of execution.
3) An important advantage of PreparedStatements is that they prevent SQL
injection attacks.
System.out.println("Enter Name");
String name = s1.next();
ps.setString(2, name);
con.close();
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
con.close();
}
}
}
int result = ps.executeUpdate();
con.close();
}
6) CallableStatement Interface :-
To call the stored procedures and functions, CallableStatement interface is
used.
import java.sql.*;
In this example, we are going to call the stored procedure INSERTR that receives
rollno, name and mob as the parameter and inserts it into the table student. Note that
you need to create the student table as well to run this application.
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@local
host:1521:xe","system","siit"); CallableStatement
stmt=con.prepareCall("{call insertR(?,?
, ?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.setLong(3,9898989898);
stmt.execute();
System.out.println("success");
}
}
Now check the table in the database, value is inserted in the student table.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT,
DOUBLE, BLOB, CLOB etc.
import java.sql.*;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection( "jdbc:oracle:thin:@localhost:
1521:xe","system","siit");
System.out.println(stmt.getInt(1));
}
}
Output: 53
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)
+" " +rs.getString(3));
}
The above example will fetch all the records of student table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
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 here.
2) set classpath:
There are two ways to set the classpath:
temporary
permanent
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;
In this example, mydb is the database name, root is the username and password is „siit‟.
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try{ Class.forName("com.mysql.jdbc.Driver
");
Connection con=DriverManager.getConnection("jdbc:mysql://l
ocalhost:3306/mydb","root","siit");
//here mydb is database name, root is username and passwor
d is „siit‟
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)
+" "+rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
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.
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 here.
2) set classpath:
There are two ways to set the classpath:
temporary
permament
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.
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String database="student.mdb";
//Here database exists in the current directory
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){ System.out.println(
rs.getString(1));
}
}}
while(rs.next()){ System.out.println(
rs.getString(1));
}
}catch(Exception ee){System.out.println(ee);}
}
}
Let's write the jdbc code to store the image in the database. Here we are using d:\\d.jpg for the
location of image. You can change it according to the image location.
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{ Class.forName("oracle.jdbc.driver.OracleDriv
er"); Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","siit");
con.close();
}catch (Exception e) {e.printStackTrace();}
}
}
If you see the table, record is stored in the database but image will not be shown. To do so,
you need to retrieve the image from the database.
Now let's write the code to retrieve the image from the database and write it into the directory
so that it can be displayed.
In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed
by the img tag.
import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[] args) {
try{ Class.forName("oracle.jdbc.driver.OracleDriv
er"); Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","siit");
fout.close();
}//end of if
System.out.println("ok");
con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}
For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:
CREATE TABLE "FILETABLE" ( "ID" NUMBER, "NAME" CLOB )
import java.io.*;
import java.sql.*;
Clob c=rs.getClob(2);
Reader r=c.getCharacterStream();
int i;
while((i=r.read())!=-1)
fw.write((char)i);
fw.close();
con.close();
System.out.println("success");
}catch (Exception e) {e.printStackTrace(); }
}
}