JDBC Statements
To Send a request the database and retrieve results from the database we need to create statements.
Type of Statements : Statement PreparedStatement
CallableStatement
Confidential
Statement
This is an interface provided by JDBC- API to process the simple JDBC queries to the Database.
Methods of Statement interface : executeUpdate() executeQuery()
setMaxRows()
getMaxRows(); close()
Confidential
Practical Implmentation of JDBC
import java.sql.*; public class Main { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:dsn1","sa",""); Statement stat=con.createStatement(); ResultSet rs=stat.executeQuery("select * from login");
} }
while(rs.next())
{ System.out.println("User Name "+rs.getString(1)); System.out.println("Pin Number "+rs.getString(2));
catch(Exception e)
} }
{
System.out.println(e); }
Confidential
PreparedStatement
This interface is provide by the JDBC-API to process parameterized Query to the database.
Methods of PreparedStatement : executeQuery() executeUpdate()
setString()
setInt() setDouble() close();
Confidential
Practical Implmentation of JDBC
import java.sql.*; public class Main {
public static void main(String[] args)
{ try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:dsn1","sa",""); PreparedStatement stat=con.prepareStatement("select * from login where userName=?"); stat.setString(1,"Rajan");
ResultSet rs=stat.executeQuery();
while(rs.next()) { System.out.println("User Name "+rs.getString(1)); System.out.println("Pin Number "+rs.getString(2)); } catch(Exception e) {
} } }
System.out.println(e);
Confidential
CallableSatement
This is an interface provided by JDBC- API to process Stored Procedure calls.
Methods of CallableStatement interface : setString() setInt()
setDouble()
getString() getInt() getDouble() close()
Confidential
Practical Implementation of JDBC
import java.sql.*; public class Main { public static void main(String[] args) { try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:dsn1","sa",""); String str="{call MyProcedure(?,?,?,?)}"; CallableStatement cs=con.prepareCall(str); cs.setString(1,"1001"); cs.registerOutParameter(2,Types.VARCHAR); cs.registerOutParameter(3,Types.VARCHAR); cs.registerOutParameter(4,Types.VARCHAR); cs.execute(); String fname=cs.getString(2); String lname=cs.getString(3); String city=cs.getString(4); System.out.println(fname); } catch(Exception e) {
} } }
System.out.println(e);
Confidential