JDBC-4 MetaData and PreparedStatement
JDBC-4 MetaData and PreparedStatement
1 Exploring ResultSetMetaData
ID NUMBER
DATE_OF_JOIN DATE
SUPERVISOR VARCHAR2
int id = rset.getInt(1);
Date rentaldate = rset.getDate(2);
String status = rset.getString(3);
12 © 2015 WIPRO LTD | WWW.WIPRO.COM
12
Mapping Database Types to Java Types
• In many cases, you can get all the columns in your result
set using the getObject() or getString() methods of
ResultSet. For performance reasons, or because you
want to perform complex calculations, it is sometimes
important to have your data in a type that exactly
matches the database column.
1. Which of the following java type is mapped to the SQL data type
BIT
a) String
b) boolean
c) int
d) byte
PreparedStatement Parameters
• A PreparedStatement does not have to execute exactly the same
query each time. You can specify parameters in the
PreparedStatement SQL string and supply the actual values for these
parameters when the statement is executed.
pstmt.setXXX(index, valu);
PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? Where ID = ?");
pstmt.setString(1, “Jeetendra");
pstmt.setInt(2, id);
pstmt.executeUpdate();
class JCreate {
public static void main(String args[]) throws SQLException {
JdbcCalls e = new JdbcCalls();
e.create(args);
}
}
23 © 2015 WIPRO LTD | WWW.WIPRO.COM
23
Example 1 on PreparedStatement(Contd.).
import java.sql.*;
class ConnectionClass {
Connection con;
Connection connectionFactory() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection
("Jdbc:Oracle:thin:@localhost:1521:ORCL","scott","tiger");
}
catch(Exception e) {
System.out.println(e);
}
return con;
}
24 } © 2015 WIPRO LTD | WWW.WIPRO.COM
24
Example 1 on PreparedStatement (Contd.).
class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void create(String[] args) throws SQLException {
String tablename = args[0];
PreparedStatement pst = con.prepareStatement("Create table
"+tablename+" (empid number(4), empname varchar(20), dept
varchar2(10), joindate date, salary number(10,2))");
pst.executeUpdate();
System.out.println(“Table created successfully”);
}
25
} © 2015 WIPRO LTD | WWW.WIPRO.COM
25
Example 1 on PreparedStatement (Contd.).
class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}