What are the benefits of using JDBC? What is prepared statement?
Benefits of using JDBC:
• JDBC enables enterprise applications to continue using existing data even if the data is stored on different database management systems.
• The combination of the Java API and the JDBC API makes the databases transferable from one vendor to another without modifications in the application code.
• JDBC is usually used to connect a user application to a 'behind the scenes' database, no matter of what database management software is used to control the database. In this function, JDBC is cross-platform or platform-independent.
• With JDBC, the complexity of connecting a user program to a 'behind the scenes' database is hidden, and makes it easy to deploy and economical to maintain.
Prepared Statement
Prepared Stat is used to execute parameterized or dynamic SQL queries.
E.g. of parameterized query:
String sql="insert into emp values(?,?,?)"; As we can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement.
It is preferred when a particular query is to be executed multiple times. We can pass the parameters to SQL query at run time using this interface.
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement.
PreparedStatement pstmt = conn.prepareStatement(queryString);
Example:
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.for Name("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, "Ramesh");
int i=stmt.executeUpdate();
System.out.println("No. of rows updated="+i);
con.close();
}catch(Exception e){
System.out.println(e);
}
Comments
Post a Comment