0% found this document useful (0 votes)
42 views

JDBC Connectivity With Ms-Access

Uploaded by

atul211988
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

JDBC Connectivity With Ms-Access

Uploaded by

atul211988
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

JDBC ConnectivitY

(1)Jdbc Connectivity with Oracle

Class.forName("oracle.jdbc.OracleDriver");

Connection conn=
DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/orcl",
"scott", "tiger");

(2) Jdbc Connectivity with Ms-Access


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");

(3) Jdbc Connectivity with MySQL


Class.forName("com.mysql.jdbc.Driver");

String url ="jdbc:mysql://localhost:3306/database_name";

Connection con = DriverManager.getConnection(url,"db_user", "db_pass");


Seven Basic Steps in Using JDBC
1. Load the driver
2. Define the Connection URL
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection

Connection
This is an interface in java.sql that specifies connection with
specific database like MYSQL,MS-Access ,Oracle ETC and java
files.

Class.forName(String driver)

This method is static . It is used to load the jdbc driver class.

Class.forName(“com.somejdbcvendor.TheirJdbcDriver)
DriverManager
It is a class of java.sql Package that controls a set of JDBC
drivers. Each driver has to be register with this class.

The JDBC classes are contained in the Java package java.sql and
javax.sql.

Package java.sql
Provides the API for accessing and processing data stored in a data source (usually a
relational database) using the JavaTM programming language.

Package javax.sql
Provides the API for server side data source access and processing from the Java TM
programming language.
Simple Java Program for Conectivity

import java.sql.*;

class Myapp1

public static void main(String s[])

try

Connection conn;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");

System.out.println("Connection Successful");

conn.close();

catch(ClassNotFoundException e)

e.printStackTrace();

catch(SQLException w)

w.printStackTrace();

}
Java Program for Retrieving Record from Database

import java.sql.*;

class Myapp2

public static void main(String s[])

int mcode,msal;

String mname,mdesig;

try

Connection conn;

Statement stmt;

ResultSet rs;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");

stmt=conn.createStatement();

rs=stmt.executeQuery("SELECT * FROM table1");

while(rs.next())

mcode=rs.getInt(1);

mname=rs.getString(2);

mdesig=rs.getString(3);

msal=rs.getInt(4);

System.out.println(mcode+" "+mname+" "+mdesig+" "+msal);


}

rs.close();

stmt.close();

conn.close();

} //end of try block

catch(ClassNotFoundException e)

e.printStackTrace();

catch(SQLException w)

w.printStackTrace();

} //End of main
} //End of class
Java Program for Updating Record

import java.sql.*;

public class Myapp3

public static void main(String st[])

int mcode,msal;

String mname,mdesig;

String buff;

Connection conn;

Statement stmt;

ResultSet rs;

int rt;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");

stmt=conn.createStatement();

buff="UPDATE table1 SET salary=30000 WHERE desig='manager'";

rt=stmt.executeUpdate(buff);

System.out.println("Number Of Rows Updated====> "+rt);

rs=stmt.executeQuery("SELECT * FROM table1");

while(rs.next())

mcode=rs.getInt(1);

mname=rs.getString(2);
mdesig=rs.getString(3);

msal=rs.getInt(4);

System.out.println(mcode+" "+mname+" "+mdesig+" "+msal);

rs.close();

stmt.close();

conn.close();

} //end of try block

catch(ClassNotFoundException e)

e.printStackTrace();

catch(SQLException w)

w.printStackTrace();

} //End of main

} //End of class
Java Program for Deleting Record

import java.sql.*;

public class Myapp4

public static void main(String st[])

int mcode,msal;

String mname,mdesig;

String buff;

Connection conn;

Statement stmt;

ResultSet rs;

int rt;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");

stmt=conn.createStatement();

buff="Delete from table1 WHERE name='kukreti'";

rt=stmt.executeUpdate(buff);

System.out.println("Number Of Rows Deleted====> "+rt);

rs=stmt.executeQuery("SELECT * FROM table1");

while(rs.next())

mcode=rs.getInt(1);

mname=rs.getString(2);
mdesig=rs.getString(3);

msal=rs.getInt(4);

System.out.println(mcode+" "+mname+" "+mdesig+" "+msal);

rs.close();

stmt.close();

conn.close();

} //end of try block

catch(ClassNotFoundException e)

e.printStackTrace();

catch(SQLException w)

w.printStackTrace();

} //End of main

} //End of class
Java Program for Inserting Record Into Database

import java.sql.*;

import java.io.*;

public class Myapp5

public static void main(String st[])

int mcode,msal;

String mname,mdesig;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Employee Code");

mcode=Integer.parseInt(br.readLine());

System.out.println("Enter Employee Name");

mname=br.readLine();

System.out.println("Enter Employee Designation");

mdesig=br.readLine();

System.out.println("Enter Employee Salary");

msal=Integer.parseInt(br.readLine());

PreparedStatement inst;
Connection conn;

Statement stmt;

ResultSet rs;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");

inst=conn.prepareStatement("INSERT INTO table1 VALUES(?,?,?,?)");

inst.setInt(1,mcode);

inst.setString(2,mname);

inst.setString(3,mdesig);

inst.setInt(4,msal);

inst.executeUpdate();

stmt=conn.createStatement();

rs=stmt.executeQuery("SELECT * FROM table1");

while(rs.next())

mcode=rs.getInt(1);

mname=rs.getString(2);

mdesig=rs.getString(3);

msal=rs.getInt(4);
System.out.println(mcode+" "+mname+" "+mdesig+" "+msal);

rs.close();
stmt.close();

inst.close();

conn.close();

} //end of try block

catch(ClassNotFoundException e)

e.printStackTrace();

catch(SQLException w)

w.printStackTrace();

catch(IOException p)

p.printStackTrace();

} //End Of main

} //End Of Class
ResultSet

public interface ResultSet extends Wrapper

A table of data representing a database result set, which is usually generated by


executing a statement that queries the database.

A ResultSet object maintains a cursor pointing to its current row of data. Initially
the cursor is positioned before the first row. The next method moves the cursor to
the next row, and because it returns false when there are no more rows in the
ResultSet object, it can be used in a while loop to iterate through the result set.

Types of Result Sets

Result Sets may have different level of functionality . For example, they
may be scrollable or non scrollable. A scrollable ResultSet has a cursor
that moves both forward and backward and can be moved to a
particular row. Also , ResultSet may be sensitive or insensitive to
changes made, while they are open ; that is , they may or may not
reflect changes to column values that are modified in the database

Three Types Of Result Sets available

(1) TYPE_FORWARD_ONLY
The result set is non scrollable, its cursor moves forward only from top
to bottom

(2) TYPE_SCROLL_INSENSITIVE

The Result set is scrollable. Its cursor can moves forward or backward .

The Result Set generally does not show changes to the underlying
database that are mde while it is open.

(3) TYPE_SCROLL_SENSITIVE

The Result set is scrollable. Its cursor can moves forward or backward .

The Result Set is sensitive to changes made while it is open. If the


Underlying column values are modified , the new values are visible ,
thus providing a dynamic view of the underlying data.

Concurrency Type

A result set may have differenet update capabilities .


JDBC API offers two Update Capabilities

(1) CONCUR_READ_ONLY

Indicates a ResultSet that cannot be updates programmatically

(2) CONCUR_UPDATABLE

Indicates a ResultSet that can be updates programmatically


ResultSet Methods
(1) boolean absolute(int row) throws SQLException

Moves the cursor to the given row number in this ResultSet object.

(2) void afterLast() throws SQLException


Moves the cursor to the end of this ResultSet object, just after the last row. This method has no effect if
the result set contains no rows.

(3) void beforeFirst() throws SQLException


Moves the cursor to the front of this ResultSet object, just before the first row. This method has no effect if
the result set contains no rows.

(4) void close() throws SQLException


Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to
happen when it is automatically closed.

(5) void deleteRow() throws SQLException


Deletes the current row from this ResultSet object and from the underlying database. This method cannot
be called when the cursor is on the insert row.

Throws:
SQLException - if a database access error occurs; the result set concurrency is CONCUR_READ_ONLY; this
method is called on a closed result set or if this method is called when the cursor is on the insert row
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

(6) boolean first() throws SQLException


Moves the cursor to the first row in this ResultSet object.

Returns: true if the cursor is on a valid row; false if there are no rows in the result set
Throws:
SQLException - if a database access error occurs; this method is called on a closed result set or the result
set type is TYPE_FORWARD_ONLY
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

(7) boolean last() throws SQLException


Moves the cursor to the last row in this ResultSet object.

Returns: true if the cursor is on a valid row; false if there are no rows in the result set

Throws:
SQLException - if a database access error occurs; this method is called on a closed result set or the result
set type is TYPE_FORWARD_ONLY
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

(8) void updateRow() throws SQLException


Updates the underlying database with the new contents of the current row of this ResultSet object. This
method cannot be called when the cursor is on the insert row.

Throws:
SQLException - if a database access error occurs; the result set concurrency is CONCUR_READ_ONLY; this
method is called on a closed result set or if this method is called when the cursor is on the insert row
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

(9) void insertRow() throws SQLException


Inserts the contents of the insert row into this ResultSet object and into the database. The cursor must be
on the insert row when this method is called.

Throws:
SQLException - if a database access error occurs; the result set concurrency is CONCUR_READ_ONLY, this
method is called on a closed result set, if this method is called when the cursor is not on the insert row, or
if not all of non-nullable columns in the insert row have been given a non-null value
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

(10) int getRow() throws SQLException


Retrieves the current row number. The first row is number 1, the second number 2, and so on.

Note:Support for the getRow method is optional for ResultSets with a result set type of
TYPE_FORWARD_ONLY

Returns: the current row number; 0 if there is no current row

Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

(11) boolean relative(int rows) throws SQLException


Moves the cursor a relative number of rows, either positive or negative. Attempting to move beyond the
first/last row in the result set positions the cursor before/after the the first/last row. Calling relative(0) is
valid, but does not change the cursor position.

Note: Calling the method relative(1) is identical to calling the method next() and calling the method
relative(-1) is identical to calling the method previous().

Parameters:
rows - an int specifying the number of rows to move from the current row; a positive number moves the
cursor forward; a negative number moves the cursor backward
Returns:
true if the cursor is on a row; false otherwise
Throws:
SQLException - if a database access error occurs; this method is called on a closed result set or the result
set type is TYPE_FORWARD_ONLY
SQLFeatureNotSupportedException - if the JDBC driver does not support this method

(12) boolean previous() throws SQLException


Moves the cursor to the previous row in this ResultSet object.

When a call to the previous method returns false, the cursor is positioned before the first row. Any
invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

If an input stream is open for the current row, a call to the method previous will implicitly close it. A
ResultSet object's warning change is cleared when a new row is read.

Returns:
true if the cursor is now positioned on a valid row; false if the cursor is positioned before the first row
Throws:
SQLException - if a database access error occurs; this method is called on a closed result set or the result
set type is TYPE_FORWARD_ONLY
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
(13) boolean next() throws SQLException
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned
before the first row; the first call to the method next makes the first row the current row; the second call
makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of
a ResultSet method which requires a current row will result in a SQLException being thrown. If the result
set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will
return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet
object's warning chain is cleared when a new row is read.

Returns:
true if the new current row is valid; false if there are no more rows
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set

How To Use These Method There is an Example


Use of Scrollable ResultsetType

import java.sql.*;
class Myapp2
{
public static void main(String s[])
{
int mcode,msal;
String mname,mdesig;
try
{
Connection conn;
Statement stmt;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR.READ_ONLY);
rs=stmt.executeQuery("SELECT * FROM table1");
rs.afterLast()
while(rs.prevoious())
{
mcode=rs.getInt(1);
mname=rs.getString(2);
mdesig=rs.getString(3);
msal=rs.getInt(4);
System.out.println(mcode+" "+mname+" "+mdesig+" "+msal);
}
rs.close();
stmt.close();
conn.close();
} //end of try block
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException w)
{
w.printStackTrace();
}
} //End of main
} //End of class

updater methods.
For Update And Insert Method Use This
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR.UPDATABLE);

The updater methods may be used in two ways:

to update a column value in the current row. In a scrollable ResultSet object, the cursor can be moved
backwards and forwards, to an absolute position, or to a position relative to the current row. The
following code fragment updates the NAME column in the fifth row of the ResultSet object rs and then
uses the method updateRow to update the data source table from which rs was derived.
rs.absolute(5); // moves the cursor to the fifth row of rs

rs.updateString("NAME", "kukreti"); // updates the NAME column of row 5 to be kukreti

rs.updateRow(); // updates the row in the data source

to insert column values into the insert row. An updatable ResultSet object has a special row associated
with it that serves as a staging area for building a row to be inserted. The following code fragment moves
the cursor to the insert row, builds a three-column row, and inserts it into rs and into the data source
table using the method insertRow.

rs.moveToInsertRow(); // moves cursor to the insert row

rs.updateString(1, "kukreti”); // updates the first column of the insert row

rs.updateInt(2,35); // updates the second column to be 35

rs.updateBoolean(3, true); // updates the third column to true

rs.insertRow();

rs.moveToCurrentRow();

ResultSetMetaData
public interface ResultSetMetaData extends Wrapper

An object that can be used to get information about the types and
properties of the columns in a ResultSet object.
Program How To Use ResultSetMetaData
import java.sql.*;
class Myapp5
{
public static void main(String s[])
{
try
{
Connection conn;
Statement stmt;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");
stmt=conn.createStatement();
rs=stmt.executeQuery("SELECT * FROM table1");
ResultSetMetaData rsmd=rs.getMetaData();
int ncol=rsmd.getColumnCount();
System.out.println(“Number Of Column In A Table” + ncol);
rs.close();
stmt.close();
conn.close();
} //end of try block
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException w)
{
w.printStackTrace();
}
} //End of main
} //End of class

ResultSetMetaData Methods
(1) int getColumnCount() throws SQLException
Returns the number of columns in this ResultSet object.

Returns: the number of columns

Throws:

SQLException - if a database access error occurs

(2) int getColumnDisplaySize(int column) throws SQLException


Indicates the designated column's normal maximum width in characters.

Parameters: column - the first column is 1, the second is 2, ...

Returns: the normal maximum number of characters allowed as the width of the
designated column

Throws:
SQLException - if a database access error occurs

(3) String getColumnName(int column) throws SQLException


Get the designated column's name.

Parameters: column - the first column is 1, the second is 2, ...


Returns: column name

Throws:
SQLException - if a database access error occurs

(4) int getColumnType(int column) throws SQLException

Retrieves the designated column's SQL type.

Parameters: column - the first column is 1, the second is 2, ...

Returns: SQL type from java.sql.Types

Throws:

SQLException - if a database access error occurs

(5) String getColumnTypeName(int column) throws SQLException


Retrieves the designated column's database-specific type name.

Parameters: column - the first column is 1, the second is 2, ...

Returns: type name used by the database. If the column type is a user-defined type, then a fully-
qualified type name is returned.

Throws:

SQLException - if a database access error occurs

(6) boolean isReadOnly(int column) throws SQLException


Indicates whether the designated column is definitely not writable.

Parameters: column - the first column is 1, the second is 2, ...


Returns: true if so; false otherwise

Throws:

SQLException - if a database access error occurs

(7) boolean isWritable(int column) throws SQLException


Indicates whether it is possible for a write on the designated column to succeed.

Parameters: column - the first column is 1, the second is 2, ...

Returns: true if so; false otherwise

Throws:

SQLException - if a database access error occurs

DataBaseMetaData
public interface DatabaseMetaData extends Wrapper
Comprehensive information about the database as a whole.
This interface is implemented by driver vendors to let users know
the capabilities of a Database Management System (DBMS) in
combination with the driver based on JDBCTM technology ("JDBC
driver") that is used with it. Different relational DBMSs often
support different features, implement features in different ways,
and use different data types. In addition, a driver may implement a
feature on top of what the DBMS offers. Information returned by
methods in this interface applies to the capabilities of a particular
driver and a particular DBMS working together. Note that as used in
this documentation, the term "database" is used generically to refer
to both the driver and DBMS.

A user for this interface is commonly a tool that needs to discover


how to deal with the underlying DBMS. This is especially true for
applications that are intended to be used with more than one
DBMS. For example, a tool might use the method getTypeInfo to
find out what data types can be used in a CREATE TABLE statement.
Or a user might call the method supportsCorrelatedSubqueries to
see if it is possible to use a correlated subquery or
supportsBatchUpdates to see if it is possible to use batch updates.

Some DatabaseMetaData methods return lists of information in


the form of ResultSet objects. Regular ResultSet methods, such as
getString and getInt, can be used to retrieve the data from these
ResultSet objects. If a given form of metadata is not available, an
empty ResultSet will be returned. Additional columns beyond the
columns defined to be returned by the ResultSet object for a given
method can be defined by the JDBC driver vendor and must be
accessed by their column label.

DatabaseMetaData Methods
(1) String getDriverName() throws SQLException
Retrieves the name of this JDBC driver.

Returns: JDBC driver name


Throws:

SQLException - if a database access error occurs

(2) String getDriverVersion() throws SQLException


Retrieves the version number of this JDBC driver as a String.

Returns: JDBC driver version

Throws:

SQLException - if a database access error occurs

(3) int getMaxCursorNameLength() throws SQLException


Retrieves the maximum number of characters that this database allows in a cursor name.

Returns: the maximum number of characters allowed in a cursor name; a result of zero means that there
is no limit or the limit is not known

Throws:

SQLException - if a database access error occurs

(4) ResultSet getTypeInfo() throws SQLException


Retrieves a description of all the data types supported by this database. They are ordered by DATA_TYPE
and then by how closely the data type maps to the corresponding JDBC SQL type.

Returns: a ResultSet object in which each row is an SQL type description

Throws:

SQLException - if a database access error occurs

(5) String getNumericFunctions() throws SQLException


Retrieves a comma-separated list of math functions available with this database. These are the Open
/Open CLI math function names used in the JDBC function escape clause.

Returns: the list of math functions supported by this database

Throws:
SQLException - if a database access error occurs

(6) String getStringFunctions() throws SQLException


Retrieves a comma-separated list of string functions available with this database.
These are the Open Group CLI string function names used in the JDBC function
escape clause.

Returns: the list of string functions supported by this database

Throws:

SQLException - if a database access error occurs

(7) String getSystemFunctions() throws SQLException


Retrieves a comma-separated list of system functions available with this database.
These are the Open Group CLI system function names used in the JDBC function
escape clause.

Returns: a list of system functions supported by this database

Throws:

SQLException - if a database access error occurs

(8) String getTimeDateFunctions() throws SQLException


Retrieves a comma-separated list of the time and date functions available with
this database.

Returns: the list of time and date functions supported by this database

Throws:
SQLException - if a database access error occurs

(9) boolean supportsStoredProcedures() throws SQLException


Retrieves whether this database supports stored procedure calls that use the
stored procedure escape syntax.

Returns: true if so; false otherwise

Throws:

SQLException - if a database access error occurs

(10) String getUserName() throws SQLException


Retrieves the user name as known to this database.

Returns: the database user name

Throws:

SQLException - if a database access error occurs

(11) int getMaxProcedureNameLength() throws SQLException


Retrieves the maximum number of characters that this database allows in a
procedure name.

Returns: the maximum number of characters allowed in a procedure name; a


result of zero means that there is no limit or the limit is not known

Throws:

SQLException - if a database access error occurs

(12) int getMaxTableNameLength() throws SQLException


Retrieves the maximum number of characters this database allows in a table
name.

Returns: the maximum number of characters allowed for a table name; a result of
zero means that there is no limit or the limit is not known

Throws:

SQLException - if a database access error occurs

(13) int getMaxUserNameLength() throws SQLException


Retrieves the maximum number of characters this database allows in a user name.

Returns: the maximum number of characters allowed for a user name; a result of
zero means that there is no limit or the limit is not known

Throws:

SQLException - if a database access error occurs

Program How To Use DatabaseMetaData


import java.sql.*;
class Myapp5
{
public static void main(String s[])
{
try
{
Connection conn;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");
stmt=conn.createStatement();
DatabseMetaData md=conn.getMetaData();
rs=md.getTypeInfo();
System.out.println(“Displaying All Primitive Dataypes”);
while(rs.next())
{
System.out.println(rs.getString(1));
}
rs.close();
conn.close();
} //end of try block
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException w)
{
w.printStackTrace();
}
} //End of main
} //End of class

Example2
import java.sql.*;
class Myapp5
{
public static void main(String s[])
{
try
{
Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");
DatabseMetaData md=conn.getMetaData();
System.out.println(“Displaying DriverName”);
String dname=md.getDriverName();
System.out.println(“DriverName= ”+dname);
System.out.println(“Displaying DriverVersion”);
String dver=md.getDriverVersion();
System.out.println(“DriverVersion= ”+dver);

System.out.println(“Displaying All NumberFunction List”);


String numfunc=md.getNumericFunctions();
System.out.println(“NumberFunction List = ”+numfunc);

System.out.println(“Displaying All StringFunction List”);


String strfunc=md.getStringFunctions();
System.out.println(“StringFunction List = ”+strfunc);

System.out.println(“Displaying All TimeandDateFunction List”);


String timedatefunc=md.getTimeDateFunctions();
System.out.println(“TimeDate Function List = ”+timedatefunc);

conn.close();
} //end of try block
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException w)
{
w.printStackTrace();
}
} //End of main
} //End of class

Statement
public interface Statement extends Wrapper
The object used for executing a static SQL statement and
returning the results it produces.
By default, only one ResultSet object per Statement object
can be open at the same time. Therefore, if the reading of
one ResultSet object is interleaved with the reading of
another, each must have been generated by different
Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet
object if an open one exists.

Methods

(1) boolean execute(String sql) throws SQLException


Executes the given SQL statement, which may return
multiple results.
(2) ResultSet executeQuery(String sql) throws SQLException
Executes the given SQL statement, which returns a single ResultSet
object.

Parameters: sql - an SQL statement to be sent to the database,


typically a static SQL SELECT statement
Returns: a ResultSet object that contains the data produced by the
given query; never null
Throws:
SQLException - if a database access error occurs, this method is
called on a closed Statement or the given SQL statement produces
anything other than a single ResultSet object
(3) int executeUpdate(String sql) throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or
DELETE statement or an SQL statement that returns nothing, such as an SQL
DDL statement.

Parameters: sql - an SQL Data Manipulation Language (DML) statement, such


as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing,
such as a DDL statement.

Returns: either (1) the row count for SQL Data Manipulation Language (DML)
statements or (2) 0 for SQL statements that return nothing

Throws:

SQLException - if a database access error occurs, this method is called on a


closed Statement or the given SQL statement produces a ResultSet object
(4) void close() throws SQLException
Releases this Statement object's database and JDBC resources immediately
instead of waiting for this to happen when it is automatically closed. It is
generally good practice to release resources as soon as you are finished with
them to avoid tying up database resources.

Calling the method close on a Statement object that is already closed has no
effect.

Note:When a Statement object is closed, its current ResultSet object, if one


exists, is also closed.

Throws:

SQLException - if a database access error occurs

PreparedStatement
public interface PreparedStatement extends Statement
Java JDBC Prepared statements are pre-compiled SQL statements.
Precompiled SQL is useful if the same SQL is to be executed repeatedly,
for example, in a loop. Prepared statements in java only save you time if
you expect to execute the same SQL over again. Every java sql prepared
statement is compiled at some point. To use a java preparedstatements,
you must first create a object by calling the Connection.prepareStatement()
method. JDBC PreparedStatements are useful especially in situations
where you can use a for loop or while loop to set a parameter to a
succession of values. If you want to execute a Statement object many
times, it normally reduces execution time to use a PreparedStatement
object instead.
Example1
import java.sql.*;
class Myapp7
{
public static void main(String s[])
{
int mcode,msal;
String mname,mdesig;
try
{
Connection conn;
PreparedStatement pstm;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");
pstm=conn.prepareStatement("select * from TableName where code=?");
pstm.setString(1,102);
rs=pstm.executeQuery();
while(rs.next())
{
mcode=rs.getInt(1);
mname=rs.getString(2);
mdesig=rs.getString(3);
msal=rs.getInt(4);
System.out.println(mcode+" "+mname+" "+mdesig+" "+msal);
}
rs.close();
pstm.close();
conn.close();

} //end of try block


catch(ClassNotFoundException e)
{

e.printStackTrace();
}
catch(SQLException w)
{
w.printStackTrace();

} //End of main
} //End of class

Example2
Inserting Record Through PreparedStatement
import java.sql.*;
import java.io.*;
public class Myapp5
{
public static void main(String st[])
{

int mcode,msal;
String mname,mdesig;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Employee Code");
mcode=Integer.parseInt(br.readLine());
System.out.println("Enter Employee Name");
mname=br.readLine();
System.out.println("Enter Employee Designation");
mdesig=br.readLine();
System.out.println("Enter Employee Salary");
msal=Integer.parseInt(br.readLine());

PreparedStatement inst;
Connection conn;
Statement stmt;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");
inst=conn.prepareStatement("INSERT INTO table1 VALUES(?,?,?,?)");
inst.setInt(1,mcode);
inst.setString(2,mname);
inst.setString(3,mdesig);
inst.setInt(4,msal);
inst.executeUpdate();
stmt=conn.createStatement();
rs=stmt.executeQuery("SELECT * FROM table1");
while(rs.next())
{
mcode=rs.getInt(1);
mname=rs.getString(2);
mdesig=rs.getString(3);
msal=rs.getInt(4);
System.out.println(mcode+" "+mname+" "+mdesig+" "+msal);
}
rs.close();
stmt.close();
inst.close();
conn.close();

} //end of try block


catch(ClassNotFoundException e)
{

e.printStackTrace();
}
catch(SQLException w)
{
w.printStackTrace();

}
catch(IOException p)
{

p.printStackTrace();
}
} //End Of main
} //End Of Class
Example3
PreparedStatement ps;
ps= conn.prepareStatement("update emptable set salary = ? where desig = ?");
pstmt.setInt(1, 9000);
pstmt.setString(2, "manager");
pstmt.executeUpdate();

Method
(1) ResultSet executeQuery() throws SQLException
Executes the SQL query in this PreparedStatement object and returns the
ResultSet object generated by the query.

Returns: a ResultSet object that contains the data produced by the query;
never null

Throws:
SQLException - if a database access error occurs; this method is called on a
closed PreparedStatement or the SQL statement does not return a ResultSet
object

(2) int executeUpdate() throws SQLException


Executes the SQL statement in this PreparedStatement object, which must be an
SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or
DELETE; or an SQL statement that returns nothing, such as a DDL statement.
Returns: either (1) the row count for SQL Data Manipulation Language (DML)
statements or (2) 0 for SQL statements that return nothing

Throws:
SQLException - if a database access error occurs; this method is called on a closed
PreparedStatement or the SQL statement returns a ResultSet object

CallableStatement
public interface CallableStatement extends PreparedStatement

The interface used to execute SQL stored procedures. The


JDBC API provides a stored procedure SQL escape syntax that
allows stored procedures to be called in a standard way for all
RDBMSs.

A CallableStatement object provides a way to call stored procedures in a


standard way for all DBMSs. A stored procedure is stored in a database; the
call to the stored procedure is what a CallableStatement object contains.
This call is written in an escape syntax that may take one of two forms: one
form with a result parameter, and the other without one. A result parameter, a
kind of OUT parameter, is the return value for the stored procedure. Both forms
may have a variable number of parameters used for input (IN parameters),
output (OUT parameters), or both (INOUT parameters). A question mark serves
as a placeholder for a parameter.

The syntax for invoking a stored procedure using the JDBC API is shown here.
Note that the square brackets indicate that what is between them is optional;
they are not themselves part of the syntax.
{call procedure_name[(?, ?, ...)]}

The syntax for a procedure that returns a result parameter is:


{? = call procedure_name[(?, ?, ...)]}

The syntax for a stored procedure with no parameters would looks this:
{call procedure_name}

Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the
IN parameter. The CallableStatement object can use all three.

Here are the definitions of each:

Parameter Description
A parameter whose value is unknown when the SQL statement is
IN created. You bind values to IN parameters with the setXXX()
methods.
A parameter whose value is supplied by the SQL statement it returns.
OUT You retrieve values from theOUT parameters with the getXXX()
methods.
A parameter that provides both input and output values. You bind
INOUT variables with the setXXX() methods and retrieve values with the
getXXX() methods.

Example How To Use CallableStatement


First Of all create Stored Procedure In Oracle
CREATE OR REPLACE PROCEDURE getEmpName
(mcode IN NUMBER, mname OUT VARCHAR) AS
BEGIN
SELECT name INTO mname FROM emptable WHERE code = mcode;
END;

Make a JDBC Program And Use above Procedure


import java.sql.*;
class Myapp
{
public static void main(String s[])
{
try
{
Connection conn;
CallableStatement stmt;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:kukreti","","");
System.out.println("Creating statement...");
String sql = "{call getEmpName (?, ?)}";
stmt = conn.prepareCall(sql);
//Bind IN parameter first, then bind OUT parameter
int mcode = 102;
stmt.setInt(1, mcode);
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
System.out.println("Executing stored procedure..." );
stmt.execute();
//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Name Of employee= “+empName);
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}//end main
}//end of class
Connection
public interface Connection extends Wrapper

A connection (session) with a specific database. SQL statements


are executed and results are returned within the context of a
connection.

A Connection object's database is able to provide information


describing its tables, its supported SQL grammar, its stored
procedures, the capabilities of this connection, and so on. This
information is obtained with the getMetaData metho d.

Note: When configuring a Connection, JDBC applications should use the


appropritate Connection method such as setAutoCommit or
setTransactionIsolation. Applications should not invoke SQL commands directly to
change the connection's configuration when there is a JDBC method available. By
default a Connection object is in auto-commit mode, which means that it
automatically commits changes after executing each statement. If auto-commit
mode has been disabled, the method commit must be called explicitly in order to
commit changes; otherwise, database changes will not be saved.

Methods
(1) void close() throws SQLException
Releases this Connection object's database and JDBC resources
immediately instead of waiting for them to be automatically
released.

Throws:
SQLException - SQLException if a database access error occurs
(2) DatabaseMetaData getMetaData() throws SQLException
Retrieves a DatabaseMetaData object that contains metadata about
the database to which this Connection object represents a
connection. The metadata includes information about the database's
tables, its supported SQL grammar, its stored procedures, the
capabilities of this connection, and so on.

Returns: a DatabaseMetaData object for this Connection object


Throws:
SQLException - if a database access error occurs or this method is
called on a closed connection

(3) void commit() throws SQLException


Makes all changes made since the previous commit/rollback
permanent and releases any database locks currently held by this
Connection object. This method should be used only when auto-
commit mode has been disabled.

Throws:
SQLException - if a database access error occurs, this method is called
while participating in a distributed transaction, if this method is
called on a closed conection or this Connection object is in auto-
commit mode

(4) void rollback() throws SQLException


Undoes all changes made in the current transaction and releases any
database locks currently held by this Connection object. This method
should be used only when auto-commit mode has been disabled.

Throws:
SQLException - if a database access error occurs, this method is called
while participating in a distributed transaction, this method is called
on a closed connection or this Connection object is in auto-commit
mode

(5) Statement createStatement() throws SQLException


Creates a Statement object for sending SQL statements to the
database. SQL statements without parameters are normally executed
using Statement objects. If the same SQL statement is executed many
times, it may be more efficient to use a PreparedStatement object.

Result sets created using the returned Statement object will by


default be type TYPE_FORWARD_ONLY and have a concurrency level
of CONCUR_READ_ONLY.
Returns: a new default Statement object
Throws:
SQLException - if a database access error occurs or this method is
called on a closed connection

(6) PreparedStatement prepareStatement(String sql)


throws SQLException
Creates a PreparedStatement object for sending parameterized SQL statements to
the database.

A SQL statement with or without IN parameters can be pre-compiled and stored in


a PreparedStatement object. This object can then be used to efficiently execute this
statement multiple times.

Note: This method is optimized for handling parametric SQL statements that benefit
from precompilation. If the driver supports precompilation, the method
prepareStatement will send the statement to the database for precompilation.
Some drivers may not support precompilation. In this case, the statement may not
be sent to the database until the PreparedStatement object is executed. This has no
direct effect on users; however, it does affect which methods throw certain
SQLException objects.

Result sets created using the returned PreparedStatement object will by default be
type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY.
Parameters: sql - an SQL statement that may contain one or more '?' IN
parameter placeholders
Returns: a new default PreparedStatement object containing the pre-compiled
SQL statement
Throws:
SQLException - if a database access error occurs or this method is called on a closed
connection

(7) CallableStatement prepareCall(String sql) throws SQLException

Creates a CallableStatement object for calling database stored procedures. The


CallableStatement object provides methods for setting up its IN and OUT
parameters, and methods for executing the call to a stored procedure.
Note: This method is optimized for handling stored procedure call statements. Some
drivers may send the call statement to the database when the method prepareCall
is done; others may wait until the CallableStatement object is executed. This has no
direct effect on users; however, it does affect which method throws certain
SQLExceptions.

Result sets created using the returned CallableStatement object will by default be
type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY.
Parameters: sql - an SQL statement that may contain one or more '?' parameter
placeholders. Typically this statement is specified using JDBC call escape syntax.
Returns: a new default CallableStatement object containing the pre-compiled SQL
statement
Throws:
SQLException - if a database access error occurs or this method is called on a closed
connection
(8) void setAutoCommit(boolean autoCommit)
throws SQLException
Sets this connection's auto-commit mode to the given state. If a connection is in
auto-commit mode, then all its SQL statements will be executed and committed as
individual transactions. Otherwise, its SQL statements are grouped into transactions
that are terminated by a call to either the method commit or the method rollback.
By default, new connections are in auto-commit mode.

The commit occurs when the statement completes. The time when the statement
completes depends on the type of SQL Statement:
For DML statements, such as Insert, Update or Delete, and DDL statements, the
statement is complete as soon as it has finished executing.
For Select statements, the statement is complete when the associated result set is
closed.
For CallableStatement objects or for statements that return multiple results, the
statement is complete when all of the associated result sets have been closed, and
all update counts and output parameters have been retrieved.

NOTE: If this method is called during a transaction and the auto-commit mode is
changed, the transaction is committed. If setAutoCommit is called and the auto-
commit mode is not changed, the call is a no-op.

Parameters: autoCommit - true to enable auto-commit mode; false to disable it


Throws:
SQLException - if a database access error occurs, setAutoCommit(true) is called
while participating in a distributed transaction, or this method is called on a closed
connection

Exception In JDBC
Exception handling allows you to handle exceptional conditions such as program-defined errors in a
controlled fashion.

When an exception condition occurs, an exception is thrown. The term thrown means that current
program execution stops, and control is redirected to the nearest applicable catch clause. If no
applicable catch clause exists, then the program's execution ends.

JDBC Exception handling is very similar to Java Excpetion handling but for JDBC, the most
common exception you'll deal with is java.sql.SQLException.

SQLException Methods:
A SQLException can occur both in the driver and the database. When such an exception occurs, an
object of type SQLException will be passed to the catch clause.

The passed SQLException object has the following methods available for retrieving additional
information about the exception:
Method Description

getErrorCode( ) Gets the error number associated with the exception.

Gets the JDBC driver's error message for an error handled by


getMessage( ) the driver or gets the Oracle error number and message for
a database error.

Gets the XOPEN SQLstate string. For a JDBC driver error, no


useful information is returned from this method. For a
getSQLState( )
database error, the five-digit XOPEN SQLstate code is
returned. This method can return null.

getNextException( ) Gets the next Exception object in the exception chain.

Prints the current exception, or throwable, and its backtrace


printStackTrace( )
to a standard error stream.

Prints this throwable and its backtrace to the print stream


printStackTrace(PrintStream s)
you specify.

Prints this throwable and its backtrace to the print writer


printStackTrace(PrintWriter w)
you specify.

JDBC - Data Types


The JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the
database. It uses a default mapping for most data types. For example, a Java int is converted to an
SQL INTEGER. Default mappings were created to provide consistency between drivers.

The following table summarizes the default JDBC data type that the Java data type is converted to
when you call the setXXX() method of the PreparedStatement or CallableStatement object or the
ResultSet.updateXXX() method.
SQL JDBC/Java setXXX updateXXX
VARCHAR java.lang.String setString updateString
CHAR java.lang.String setString updateString
LONGVARCHAR java.lang.String setString updateString
BIT boolean setBoolean updateBoolean
NUMERIC java.math.BigDecimal setBigDecimal updateBigDecimal
TINYINT byte setByte updateByte
SMALLINT short setShort updateShort
INTEGER int setInt updateInt
BIGINT long setLong updateLong
REAL float setFloat updateFloat
FLOAT float setFloat updateFloat
DOUBLE double setDouble updateDouble
VARBINARY byte[ ] setBytes updateBytes
BINARY byte[ ] setBytes updateBytes
DATE java.sql.Date setDate updateDate
TIME java.sql.Time setTime updateTime
TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp
CLOB java.sql.Clob setClob updateClob
BLOB java.sql.Blob setBlob updateBlob
ARRAY java.sql.Array setARRAY updateARRAY
REF java.sql.Ref SetRef updateRef
STRUCT java.sql.Struct SetStruct updateStruct

The setXXX() and updateXXX() methods enable you to convert specific Java types to specific
JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java
type to a JDBC data type.

ResultSet object provides corresponding getXXX() method for each data type to retrieve column
value. Each method can be used with column name or by its ordinal position.
SQL JDBC/Java setXXX getXXX
VARCHAR java.lang.String setString getString
CHAR java.lang.String setString getString
LONGVARCHAR java.lang.String setString getString
BIT boolean setBoolean getBoolean
NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal
TINYINT byte setByte getByte
SMALLINT short setShort getShort
INTEGER int setInt getInt
BIGINT long setLong getLong
REAL float setFloat getFloat
FLOAT float setFloat getFloat
DOUBLE double setDouble getDouble
VARBINARY byte[ ] setBytes getBytes
BINARY byte[ ] setBytes getBytes
DATE java.sql.Date setDate getDate
TIME java.sql.Time setTime getTime
TIMESTAMP java.sql.Timestamp setTimestamp getTimestamp
CLOB java.sql.Clob setClob getClob
BLOB java.sql.Blob setBlob getBlob
ARRAY java.sql.Array setARRAY getARRAY
REF java.sql.Ref SetRef getRef
STRUCT java.sql.Struct SetStruct getStruct

You might also like