Font Awesome Icons
Tutorial
Menu
Core Java
AWT
Swing
Servlet
JSP
JDBC
Spring
Hibernate
JAVA JDBC
JDBC Introduction
JDBC Driver
DB Connectivity Steps
Connectivity with Oracle
Connectivity with MySQL
DriverManager
Connection
Statements
ResultSet
PreparedStatement
Store image
Retrieve image
Store file
Retrieve file
CallableStatement
Transaction Management
JDBC Basic Query
JAVA JDBC
JDBC Introduction
JDBC Driver
DB Connectivity Steps
Connectivity with Oracle
Connectivity with MySQL
DriverManager
Connection
Statements
ResultSet
PreparedStatement
Store image
Retrieve image
Store file
Retrieve file
CallableStatement
Transaction Management
JDBC Basic Query
PreparedStatement
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
Let’s see the example of parameterized query:
String sql=”insert into emp values(?,?,?)”;
The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.
instance of PreparedStatement
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:
public
PreparedStatement prepareStatement(String query)
throws
SQLException{}
Methods of PreparedStatement interface
Example of PreparedStatement interface that inserts the record:
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”,”system”,”oracle”);
PreparedStatement stmt=con.prepareStatement(“insert into Emp values(?,?)”);
stmt.setInt(1,101); //1 specifies the first parameter in the query
stmt.setString(2,“Alok”);
int i=stmt.executeUpdate();
System.out.println(i+” records inserted”);
con.close();
}
catch(Exception e){ System.out.println(e);
}
}
}
Example of PreparedStatement interface that updates the record
PreparedStatement stmt=con.prepareStatement(“update emp set name=? where id=?”);
stmt.setString(1,“Alok”); //1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);
int i=stmt.executeUpdate();
System.out.println(i+” records updated”);
Example of PreparedStatement interface that deletes the record
PreparedStatement stmt=con.prepareStatement(“delete from emp where id=?”);
stmt.setInt(1,101);
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));
}
Hi, Welcome to etechvidya
Home
About Us
Tutorial