You are on page 1of 83

Advanced Java Programming

Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
JDBC Architecture
The JDBC Architecture can be classified
into two layers:
1. JDBC Application Layer
2. JDBC Driver Layer
ODBC
• ODBC stands for Open Database
Connectivity
• A standard or open application
programming interface (API) for accessing a
database.
• ODBC provides a C interface for database
access on Windows environment.
JDBC
• JDBC stands for Java Database Connectivity.
• It is a standard Java API for connecting
programs written in Java to the data in
relational databases.
• JDBC works with Java on a variety of
platforms, such as Windows, Mac OS, and
the various versions of UNIX.
JDBC Driver
• JDBC Driver is a software component that
enables java application to interact with the
database. There are 4 types of JDBC drivers:
 JDBC-ODBC bridge driver
 Native-API driver (partially java driver)
 JDBC-Net pure Java/ Network-Protocol driver
(fully java driver)
 Pure Java Driver / Thin driver / Database-
Protocol driver(fully java driver)
JDBC-ODBC bridge driver
• The JDBC type 1 driver, also known as the JDBC-ODBC
bridge driver.
• The JDBC-ODBC bridge driver uses ODBC driver to connect
to the database. The JDBC-ODBC bridge driver converts
JDBC method calls into the ODBC function calls.
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method
call is converted into the ODBC function calls.
• The ODBC driver needs to be installed on the
client machine.
Native API driver
• The JDBC type 2 driver, also known as the Native-API driver
• The Native API driver uses the Local native libraries
provided by the database vendors to access databases.
• The JDBC driver maps the JDBC calls to the
native method calls, which are passed to the
native call level interface(CLI).
• This interface consists of functions written
in C to access database.
• To use the Type-2 driver CLI needs to be
loaded on the client computer as opposed to the
JDBC-ODBC bridge driver, the Native API java
driver does not have an ODBC intermediate layer.
As a result, this driver has a better performance
than the JDBC-ODBC bridge driver.
• This driver is used for Network based
applications.
Advantage:
• performance upgraded than JDBC-ODBC
bridge driver.
Disadvantage:
• The Native driver needs to be installed on the
each client machine.
• The Vendor client library needs to be installed
on client machine.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
 JDBC Architecture
 JDBC Drivers:
a) JDBC-ODBC Bridge Driver.
b) Native API Partly Java Driver.
JDBC-Net pure Java Driver
• The JDBC type 3 driver, also known as the Pure Java driver for
database middleware. It is a database driver implementation
which makes use of a middle tier between the calling program and
the database.
• The middle-tier (application server) converts JDBC calls directly or
indirectly into a vendor-specific database protocol. It is fully
written in java.
• The client portion consists of pure java
functions and the server portion contains java
and native methods.
• The java applications sends JDBC calls to
the JDBC-Net pure java driver client portion,
which in turn translate JDBC calls into
database calls.
• The database calls are sent to the server
portion of the JDBC-Net pure java driver that
forward the request to the database.
• when you use the JDBC-Net pure java
driver native libraries are loaded on the
server.
Advantage:
• No client side library is required because of
application server that can perform many tasks
like auditing, load balancing, logging etc.
Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in
the middle tier.
• Maintenance of Network Protocol driver
becomes costly because it requires database-
specific coding to be done in the middle tier.

.
Native Protocol Pure Java Driver/Thin driver
• The JDBC type 4 driver, also known as the Direct to Database Pure
Java Driver, is a database driver implementation that
converts JDBC calls directly into a vendor- specific database
protocol.
• That is why it is known as thin driver. It is fully written in Java
language.
• As opposed to the other JDBC
driver, you do not require to install any
vender specific libraries to use the Type
4 driver.
• Data direct technologies provides
Type 4 driver for various databases such
as MS SQL server, DB2.
• This driver is usually used for
enterprise applications.
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server
side.
Disadvantage:
• Drivers depend on the Database.

.
JDBC two tier model
• In a two-tier model, a Java application communicates
directly with the database, via the JDBC driver.

.
JDBC three tier model
• In a three-tier model, a Java application communicates
with a middle tier component that functions as an
application server. The application server talks to a
given database using JDBC.

.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
 JDBC Drivers:
c) JDBC-Net pure Java Driver.
d) Native-Protocol pure java Driver/ Thin
Driver.
JDBC API
• The JDBC API provides the following interfaces
and classes defined in java.sql & javax.sql
packages−
• DriverManager Class
• Driver Interface
• Connection Interface
• Statement Interface
• ResultSet Interface
• SQL Exception class
.
Steps to Follow to connect with database &
retrieving results

1. Load a driver.

2. Connect to database.

3. Create and Execute JDBC statements.

4. Handle SQL exceptions.


1. Loading a driver
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().
.
Using the forName() Method:
• Using the forName() Method:
The forName() method is available in the
java.lang package.
• The forName()method loads the JDBC
driver and register the driver with the driver
manager.
• The syntax is:
Class.forName(“<driver_name>”);
• e.g. To load the JDBC-ODBC bridge driver
We can write like this:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Using registerDriver() Method
• Create the instance of the driver class to
load a JDBC Driver.
• The syntax is:
Driver d=new <driver name>;
e.g. Driver d=new sun.jdbc.odbc.JdbcOdbcDriver()
• Once created the Driver class object call
the registerDriver() method to register it the
DriverManager class.
e.g. DriverManager.registerDriver(d);
2. Connect to a Database
• Connection Interface
A Connection is the session between
java
application and database. The
interface is Connection of
aPreparedStatement, factory
and DatabaseMetaData.
The Connection interface Statement,
provide many
methods for transaction management
like commit(),rollback() etc.

.
Create an object of the connection interface
to establish a connection of java application with a
database.
The DriverManager class provides the
getConnection() method to create connection
object.
1. Connection getConnection(String <url>):
The syntax for a JDBC url that is passed as a
parameter to getConnection() method is:
<protocol>:<subprotocol>:<subname>
A JDBC url has following three components:
1) protocol name:
Indicates the name of the protocol that is
used to access a database.
2) sub protocol name:
Indicates the mechanism to retrive data from a
database.
3) subname:
Indicate the Data Source Name(DSN) that
contains database information such as name of
database, Location of the database server, user
name, password to access database server.
e.g.
String url=“jdbc:odbc:MydataSource”;
Connection con=DriverManager.getConnection(url);
2. Connection getConnection(String<url>,
String<username>, String<password>):
Accepts a JDBC url of a database. It also accepts
the user name and password of the authorized
database server.
e.g.
String url=“jdbc:odbc:MyDataSource”;
Connection con=DriverManager.getConnection(url,
“new user”, “new password”);
3. Connection getConnection(String<url>,
properties<properties>):
Accepts the JDBC url of a database and properties
parameter which specify information such as user
name and password in the properties object using
setProperty() method.
e.g.
String url=“jdbc:odbc:MyDataSource”;
Properties p=new Properties();
p.setProperty(“user”,”new user”);
p.setProperty(“password”,new password”);
Connection con=DriverManager.getConnection(url,p);
Commonly used methods of DriverManager class
Method Description

public static void registerDriver(Driver driver); is used to register the given driver
with DriverManager.

is used to deregister the given


public static void deregisterDriver(Driver driver); driver (drop the driver from the
list) with DriverManager.

public static Connection getConnection(String url); is used to establish the connection


with the specified url.

public static Connection getConnection(String is used to establish the connection


url,String userName,String password); with the specified url, username
and password.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
 JDBC API classes & Interfaces.
 DriverManager class.
 Driver Interface.
 Connection Interface.
JDBC API
• The JDBC API provides the following interfaces
and classes defined in java.sql & javax.sql
packages−
• DriverManager Class
• Driver Interface
• Connection Interface
• Statement Interface
• ResultSet Interface
• SQL Exception class
.
Steps to Follow to connect with database &
retrieving results

1. Load a driver.

2. Connect to database.

3. Create and Execute JDBC statements.

4. Handle SQL exceptions.


3. Create and Execute JDBC statements
• Statement Interface
 The Statement interface provides
methods to execute queries with the
database. It provides factory method to get
the object of ResultSet.
 Create a statement object to send
request to and retrieve result from a
database.

.
 The Connection object provides the
createStatement() method to create a statement
object.
 e.g.
Connection
con=DriverManager.getConnection(“jdbc:odbc:MyD
ataSource”,”new user”,”new password”);
Statement stmt=con.createStatement();
1. ResultSet executeQuery(String str):
 Execute an SQL statement and return a
single object of the type ResultSet.
 The executeQuery() method should be
used when we need to retrive data from a
database table using the SELECT statement.
 The Syntax is:
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(<SQL stmt>);
 The stmt is a reference to the object of
Statement interface. The executeQuery()
method execute an SQL statement and result
retrived from database is stored in rs the
2. int executeUpdate(String str):
 Executes the SQL statements and returns
the number of data rows that are affected after
processing the SQL statement.
 When we need to modify data in a database
table using the Data Manipulation
Language(DML) statements INSERT, DELETE and
UPDATE.
 The Syntax is:
Statement stmt=con.createStatement();
int count=stmt.executeUpdate(<SQL stmt>);
 The executeUpdate() method executes an
SQL stmt. and number of rows affected in a
3. boolean execute(String str):
 Executes an SQL statements and returns
a boolean value.
 We can use this method when the type
of SQL statement passed as a parameter is
not known or when the statements being
executed returns a resultset or an update
count.
 The execute() method returns true if the
result of the SQL statement is an object of
ResultSet and false if it is an update count.
e.g.
Statement stmt=con.createStatement();
Commonly used methods of Statement interface

Method Description

public ResultSet executeQuery(String sql); used to execute SELECT query. It returns


the object of ResultSet.

public int executeUpdate(String sql); used to execute specified query, it may be


create, drop, insert, update, delete etc.

public boolean execute(String sql); used to execute queries that may return
multiple results.

public int[] executeBatch(); used to execute batch of commands.

.
Accessing ResultSet Interface

• ResultSet Interface
When we execute a query to retrive data
from a table using a Java Application, the output
of query is stored in a ResultSet object in tabular
format.
The ResultSet object maintains a cursor that
moves in the forward direction only.
As a result it moves from the first row to the
last row in the ResultSet.
Types of ResultSet:
1. Read only:
Allows to only read the rows in a ResultSet
object.
2. Forward only:
Allow to move the resultset cursor from first row
to last row in forward direction only.
3. Scrollable:
Allow to move the resultset cursor forward and
backward through the resultset.
4. Updatable:
Allow to update the resultset rows retrived from
a database table.
we can specify the type of ResultSet object using
the createStatement() method of connection interface.
Methods of ResultSet Interface:

1. boolean first(): shifts the resultset cursor to


first row.
2. boolean isfirst(): determine that rseultset
cursor points to first row or not.
3. boolean beforefirst(): shifts the resultset
cursor before the first row.
4. booean isbeforefirst(): determine that
resultset cursor points before the first row.
5. boolean last(): shifts the resultset cursor to
the last row.
6. boolean islast(): determine that resultset
4. Handling SQL Exceptions:

The java.sql package provides the


SQLException class which is derived from the
java.lang.Exception class.
The SQLException is thrown by various
methods in JDBC API and enables to determine
the reason of the errors that occur while
connecting a java application to a database.
we can catch the SQLException in java
application using the try and catch exception
handling block.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
 JDBC API classes & Interfaces.
 Statement Interface.
 ResultSet Interface.
 SQLExceptions
Prepared Statement
• The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
• Example:
String sql="insert into emp values(?,?,?)";
Here, we are passing parameter (?) for the values. Its value will
be set by calling the setter methods of PreparedStatement.
• to get the instance of PreparedStatement the
prepareStatement() method of Connection interface is used
to return the object of PreparedStatement.
• Syntax:
PreparedStatement prepareStatement(String query)throws SQLExce
ption{}

.
Methods of Prepared Statement
interface
The preparedStatement interface inherits
the following methods to execute SQL stmt.
From the Statement interface.
1. ResultSet executeQuery():
Executes a SELECT statement and returns
the result in a ResultSet object.
2. int executeUpdate():
Executes an SQL stmt. INSERT, UPDATE or
DELETE and returns the count of rows affected.
3. boolean execute():
Executes an SQL stmt. And returns a
e.g.
Consider we have to retrieve the details of
an author by passing author id at runtime.
SELECT * FROM authors WHERE au_id=?
To submit such parameterized query to a
database from an application, we need to create
PreparedStatement object using
perpareStatement() method of the Connection
object.
stmt=con.prepareStatement(“SELECT * FROM
authors WHERE au_id=?”);
The prepareSttaement() method of the
Connection object takes an SQL stmt. as an
The SQL stmt. Can contain ‘?’ symbol as
placeholder that can be replaced by input
parameter at runtime.
Before executing the SQL stmt. Specified in
perpareStatement object we must set the value
for ‘?’ parameter this is done by calling
appropriate setxxx() method where xxx is a
datatype of the parameter.
stmt.setString(1,”1001”);
ResultSet rs=stmt.executeQuery();
The first parameter of setString() method
specifies the index value of the ‘?’ placeholder
and the second parameter is used to set ‘1001’
1. Retrieving rows:
we can use the following code to retrive the
books written by an author from the titles table
using the PreparedStatement object.

String str=“SELECT * FROM titles WHERE au_id=?”;


PreparedStatement ps=con.prepareStatement(str);
ps.setString(1,”1001”);
ResultSet rs=ps.executeQuery();
2. Inserting rows:
we can use the following code to create a
PreparedStatement object that insert a row into
authors table at runtime.

String str=“INSERT INTO authors(au_id, au_name,


au_pname) VALUES(?,?,?)”);
PerparedStatement ps=con.prepareStatement(str);
ps.setString(1,”1001”);
ps.setString(2,”Herbert schildt”);
ps.setString(3,”Tata Hills”);
int rt=ps.executeUpdate();
3.Updating & Deleting rows:
String str=“UPDATE authors SET State=? WHERE
City=?”;
PreparedStatement ps=con.prepareStatement(str);
ps.setString(1,”CA”);
ps.setString(2,”Oakland”);
int rt=ps.executeUpdate();
For Deleting rows:
String str=“DELETE FROM authors WHERE
au_name=?”;
PerparedStatement ps=con.perpareStatement(str);
ps.setString(1,”Herbert Schildt”);
int rt=ps.executeUpdate();
Methods of PreparedStatement interface
Method Description

public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.

public void setString(int paramIndex, sets the String value to the given
String value) parameter index.

public void setFloat(int paramIndex, sets the float value to the given
float value) parameter index.

public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.

public int executeUpdate() executes the query. It is used for


create, drop, insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an


instance of ResultSet.

.
Common JDBC Components (cont’d..)
• Connection Interface
A Connection is the session between
java
application and database. The
interface is Connection of
aPreparedStatement, factory
and DatabaseMetaData.
The Connection interface Statement,
provide many
methods for transaction management
like commit(),rollback() etc.

.
Commonly used methods of Connection interface
Method Description

public Statement createStatement(); creates a statement object that can be


used to execute SQL queries.

public void setAutoCommit(boolean status); It is used to set the commit status. By


default it is true.

public void commit(); It saves the changes made since


the
previous commit/rollback permanent.
public void rollback(); Drops all changes made since
the previous commit/rollback.

closes the connection and Releases


public void close(); a
JDBC resources immediately.
Common JDBC Components (cont’d..)
• Statement Interface
The Statement interface provides methods to
execute queries with the database. It provides
factory method to get the object of ResultSet.

.
Commonly used methods of Statement interface

Method Description

public ResultSet executeQuery(String sql); used to execute SELECT query. It returns


the object of ResultSet.

public int executeUpdate(String sql); used to execute specified query, it may be


create, drop, insert, update, delete etc.

public boolean execute(String sql); used to execute queries that may return
multiple results.

public int[] executeBatch(); used to execute batch of commands.

.
Prepared Statement
• The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
• Example:
String sql="insert into emp values(?,?,?)";
Here, we are passing parameter (?) for the values. Its value will
be set by calling the setter methods of PreparedStatement.
• to get the instance of PreparedStatement the
prepareStatement() method of Connection interface is used
to return the object of PreparedStatement.
• Syntax:
public PreparedStatement prepareStatement(String query)throws
SQLExce
ption{}
.
Methods of PreparedStatement interface
Method Description

public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.

public void setString(int paramIndex, sets the String value to the given
String value) parameter index.

public void setFloat(int paramIndex, sets the float value to the given
float value) parameter index.

public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.

public int executeUpdate() executes the query. It is used for


create, drop, insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an


instance of ResultSet.

.
Common JDBC Components (cont’d..)
• ResultSet Interface
The object of ResultSet maintains a cursor
pointing to a particular row of data. Initially,
cursor points to before the first row.

.
Commonly used methods of ResultSet interface
Method Description
public boolean next(); is used to move the cursor to the one row next from
the current position.
public boolean previous(); is used to move the cursor to the one row previous
from the current position.
public boolean first(); is used to move the cursor to the first row in result set
object.
public boolean last(); is used to move the cursor to the last row in result set
object.
public boolean absolute(int row); is used to move the cursor to the specified row number
in the ResultSet object.
public int getInt(int columnIndex); is used to return the data of specified column index of
the current row as int.
public int getInt(String columnName); is used to return the data of specified column name of
the current row as int.
public String getString(int columnIndex); is used to return the data of specified column index of
the current row as String.
public String getString(String is used to return the data of specified column name of
columnName); the current row as String.

.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
 JDBC API classes & Interfaces.
 PreparedStatement Interface.
 ResultSet Interface.
 SQLExceptions
Connecting to Database
• There are 5 steps to connect any java
application with the database in java using
JDBC. They are as follows:

1. Register the driver class


2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1.Register the driver class
• The Class.forName() method is used to register the
driver class. This method is used to dynamically load
the driver class.

• Syntax of forName() method


public static void forName(“<driver name>”)throws ClassNotFoundException

• Example to register with JDBC-ODBC Driver

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

.
1.Register the driver class

• The registerDriver() method is used to register


the driver class.

• Syntax of registerDriver() method


Driver d=new <driver name>;
DriverManager.registerDriver(d);

• Example to register with JDBC-ODBC Driver


Driver d=new sun.jdbc.odbc.JdbcOdbcDriver();
DriverManager.registerDriver(d);
2. Creating connection
• The DriverManager.getConnection() method is used
to establish connection with the database.

• Syntax of getConnection() method


 public static Connection getConnection(String url)throws SQLException
 public static Connection getConnection(String url,String name,String password)

throws SQLException
 public static Connection getConnection(String url,Properties<properties>)

throws SQLException

.
2. Creating connection

• Example establish connection with


Database
 Connection con = DriverManager.getConnection("jdbc:odbc:DemoDB");

 Connection con = DriverManager.getConnection


("jdbc:odbc:DemoDB","username","password");

 Properties p=new Properties();

p.setProperty(“user”,”new User”);

p.setProperty(“password”,”new password”);

Connection con = DriverManager.getConnection


("jdbc:odbc:DemoDB",p);
3. Creating statement

• The createStatement() method of Connection


interface is used to create statement. The
object of statement is responsible to execute
queries with the database.
• Syntax of createStatement() method

public Statement createStatement()throws SQLException

• Example to create the statement object


Statement stmt=con.createStatement();
.
3. Creating statement
• The prepareStatement() method of Connection
interface is used to create statement. The object
of PreparedStatement is responsible to execute
queries with the database.
• Syntax of prapareStatement() method

public PreparedStatement prepareStatement()throws SQLException

• Example to create the prepareStatement object


PreparedStatement
stmt=con.prepareStatement();
4. Executing queries
• The executeQuery() , executeUpdate() &execute() method
of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that
can be used to get all the records of a table.

• Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws
SQLException

• Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
} .
4. Executing queries
• The executeUpdate() method of Statement interface is used to
execute queries to the database. This method returns int result
i.e.how many no of rows in table are updated after execution.

• Syntax of executeUpdate() method


public int executeQuery(String sql)throws SQLException

• Example to execute query


String sql="delete from Student1 where Roll_no=2";

Statement st=con.createStatement();

st.executeUpdate(sql);

ResultSet rs=st.executeQuery("select * from Student1");

while(rs.next())

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

}
4. Executing queries
• The execute() method of Statement interface is used to
execute queries to the database. This method returns a
boolean value.

• Syntax of executeQuery() method


public boolean execute(String sql)throws SQLException

• Example to execute query


String sql="Update Product set Product_name='Computer'where Product_name='tv’”;

Statement st=con.createStatement();

st.execute(sql);

ResultSet rs=st.executeQuery("select * from Product");

while(rs.next())

System.out.println(rs.getString(1)); }
5. Closing connection
• By closing connection object statement and
ResultSet will be closed automatically. The close()
method of Connection interface is used to close
the connection.

• Syntax of close() method


public void close()throws SQLException

• Example to close connection


con.close();

.
import java.sql.*;
class sample
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
String url="jdbc:odbc:DSN211";
Connection con=DriverManager.getConnection(url);
System.out.println("Connection established");
String sql="Select * from student where Percentage>=70";
.
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
}
ps.close();
con.close();
rs.close();
}
catch(Exception e)
{}
}
}
import java.sql.*;
class MysqlCon{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sun","root",“123");
//here sun is database name, root is username and password
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);
}
} //CD:\ePparromt gernat mfoCFomilepuste\rJava\jre1.6.0\lib\ext
AJP- Unit-V 34
Engineering
Prepared Statement Example
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{ Class.forName("oracle.jdbc.driver.OracleDriv
er");
Connection
con=DriverManager.getConnection("jdbc:mysql:/
/localhost:3306/sun","root",“123");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");


stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan"); //2 specifies the second parameter in the query

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();

}catch(Exception e)
{ System.out.println(e);}

Department of Computer
AJP- Unit-V 35
}Engineering

You might also like