0% found this document useful (0 votes)
78 views

JDBC-4 MetaData and PreparedStatement

Uploaded by

r
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

JDBC-4 MetaData and PreparedStatement

Uploaded by

r
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

JDBC

MetaData and PreparedStatement

1 © 2015 WIPRO LTD | WWW.WIPRO.COM


MetaData and PreparedStatement

2 © 2015 WIPRO LTD | WWW.WIPRO.COM


Agenda

1 Exploring ResultSetMetaData

2 Using PreparedStatement Object

3 © 2015 WIPRO LTD | WWW.WIPRO.COM


Objectives

At the end of this module, you will be able to:

– Analyze how to use the Metadata objects to retrieve


more information about the database or the result set

– Create and execute a query using PreparedStatement


object

4 © 2015 WIPRO LTD | WWW.WIPRO.COM


4
The ResultSetMetaData Object

• ResultSetMetaData is an interface which contains methods to


get information about the types and properties of the columns
in the ResultSet object

• ResultSetMetaData object provides metadata, including:


– Number of columns in the result set
– Column type
– Column name
In JDBC, you use the ResultSet.getMetaData() method to return
a ResultSetMetaData object, which describes the data coming
back from a database query. This object can be used to
find out about the types and properties of the columns
in your ResultSet.
5 © 2015 WIPRO LTD | WWW.WIPRO.COM
5
How to obtain ResultSetMetadata?

1. To get the ResultSetMetaData object

ResultSetMetaData rsmd = rset.getMetaData();

2. Use the object’s methods to get the metadata

ResultSetMetaData rsmd = rset.getMetaData();


for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String colname = rsmd.getColumnName(i);
int coltype = rsmd.getColumnType(i);

}

6 © 2015 WIPRO LTD | WWW.WIPRO.COM


6
Example on ResultSetMetaData
import java.sql.*;
class MakeConnection4{
Connection conn;
Statement stmt;
ResultSet rs;
ResultSetMetaData rsmd;
MakeConnection4(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("Jdbc:Oracle:thin:@localhost
:1521:orcl","scott","tiger");
stmt=conn.createStatement();
rs=stmt.executeQuery("Select * from emp");

7 © 2015 WIPRO LTD | WWW.WIPRO.COM


7
Example on ResultSetMetaData(Contd.).
rsmd = rs.getMetaData();
int noc = rsmd.getColumnCount();
System.out.println("Number Of Columns : "+noc);
for(int i=1;i<=noc;i++) {
System.out.print("Column "+i+" =
"+rsmd.getColumnName(i)+"; ");
System.out.print("Column Type =
"+rsmd.getColumnType(i)+"; ");
System.out.println("Column Type Name =
"+rsmd.getColumnTypeName(i)+";");
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
8 © 2015 WIPRO LTD | WWW.WIPRO.COM
8
Example on ResultSetMetaData (Contd.).
public class RSMetaDataExample {
public static void main(String args[]) {
new MakeConnection4();
}
}

9 © 2015 WIPRO LTD | WWW.WIPRO.COM


9
• The example shows how to use a
ResultSetMetaData object to determine the following
information about the ResultSet:
• The number of columns in the ResultSet.
• The name of each column
• The American National Standards Institute (ANSI)
SQL type for each column
• java.sql.Types
• The java.sql.Types class defines constants that are
used to identify ANSI SQL types.
ResultSetMetaData.getColumnType() returns an
integer value that corresponds to one of these
constants.

10 © 2015 WIPRO LTD | WWW.WIPRO.COM


Example on ResultSetMetaData (Contd.).

11 © 2015 WIPRO LTD | WWW.WIPRO.COM


11
Mapping Database Types to Java Types
ResultSet maps 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.
ResultSet rset = stmt.executeQuery
("select ID, DATE_OF_JOIN, SUPERVISOR
from STUDENT"); Col Name Type

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.

13 © 2015 WIPRO LTD | WWW.WIPRO.COM


Mapping Database Types to Java Types (Contd.).
Java data type
SQL data type
Simply mappable Object mappable
CHARACTER String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BIT boolean Boolean
TINYINT byte Integer
SMALLINT short Integer
INTEGER int Integer
BIGINT long Long
REAL float Float
FLOAT double Double
DOUBLE PRECISION double Double
BINARY byte[]
VARBINARY byte[]
LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp

14 © 2015 WIPRO LTD | WWW.WIPRO.COM


14
Quiz

1. Which of the following java type is mapped to the SQL data type
BIT
a) String
b) boolean
c) int
d) byte

2. What object is returned, when you invoke the getMetaData


method on the ResultSet object
a) StatementMetaData Answers :
b) ResultSetMetaData
c) DatabaseMetaData 1 :b
2 :b
d) ConnectionMetaData
.
15 © 2015 WIPRO LTD | WWW.WIPRO.COM
15
The PreparedStatement Object
• Using PreparedStatement in place of Statement interface will improve
the performance of a JDBC program

• PreparedStatement is inherited from Statement; the difference is that a


PreparedStatement holds precompiled SQL statements

• If you execute a Statement object many times, its SQL statement is


compiled each time. PreparedStatement is more efficient because its
SQL statement is compiled only once, when you first prepare the
PreparedStatement. After that, each time you execute the SQL
statement in the PreparedStatement, the SQL statement does not have
to be recompiled

• Therefore, if you need to execute the same SQL statement several


times within an application, it is more efficient to use
PreparedStatement than Statement

16 © 2015 WIPRO LTD | WWW.WIPRO.COM


16
The PreparedStatement Object

• PreparedStatement is inherited from Statement; the difference is that


a PreparedStatement holds precompiled SQL statements.
• If you execute a Statement object many times, its SQL statement is
compiled each time. PreparedStatement is more efficient because its
SQL statement is compiled only once, when you first prepare the
PreparedStatement. After that, each time you execute the SQL
statement in the PreparedStatement, the SQL statement does not
have to be recompiled.

• Therefore, if you need to execute the same SQL statement several


times within an application, it is more efficient to use
PreparedStatement than Statement.

17 © 2015 WIPRO LTD | WWW.WIPRO.COM


The PreparedStatement Object

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.

• The following slide shows how to supply parameters and execute a


PreparedStatement.

18 © 2015 WIPRO LTD | WWW.WIPRO.COM


The PreparedStatement Object

• A prepared statement can contain variables that you supply


each time you execute the statement
• 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.
• The following slide shows how to supply parameters and
execute a PreparedStatement.

19 © 2015 WIPRO LTD | WWW.WIPRO.COM


How to Create a PreparedStatement?

1. Register the driver and create the database connection

2. Create the prepared statement, identifying variables with


a question mark (?)
PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? where ID = ?");
PreparedStatement pstmt =
conn.prepareStatement("select SUPERVISOR from
STUDENT where ID = ?");
Once the connection object is obtained, the prepareStatement method is called on it
to obtain the PreparedStatement object. However, in this case, while creating it,
itself, the SQL statement is provided as a parameter to the method. The
variable portions of the SQL statement are provided as a question mark (?) so
that the values can be supplied dynamically before execution of the
20
statement. 20
© 2015 WIPRO LTD | WWW.WIPRO.COM
How to execute PreparedStatement?

1. Supply values for the variables

pstmt.setXXX(index, valu);

Specifying Values for the Bind Variables


You use the PreparedStatement.setXXX() methods to supply values for the
variables in a prepared statement. There is one setXXX() method for each
Java type: setString(), setInt(), and so on.
You must use the setXXX() method that is compatible with the SQL type of
the variable. In the example on the slide, the first variable is updating a
VARCHAR column, so we need to use setString() to supply a value for the
variable. You can use setObject() with any variable type.
Each variable has an index. The index of the first variable in the prepared
statement is 1, the index of the second is 2, and so on. If there is only one
variable, its index is one. The index of a variable is passed to the setXXX()
method.
21 © 2015 WIPRO LTD | WWW.WIPRO.COM
21
How to execute PreparedStatement?

2. Execute the statement


pstmt.executeQuery();
pstmt.executeUpdate();

PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? Where ID = ?");
pstmt.setString(1, “Jeetendra");
pstmt.setInt(2, id);
pstmt.executeUpdate();

Closing a Prepared Statement


If you close a prepared statement, you will have to prepare it again.

22 © 2015 WIPRO LTD | WWW.WIPRO.COM


22
Example 1 on PreparedStatement
/* This class is executed in the following manner :
if you want to create the table, you will execute as
java JCreate table1
where table1 is the name of the table. The table table1 is created with the
following columns
empid, empname, dept, joindate, salary
*/
import java.sql.*;

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.).

26 © 2015 WIPRO LTD | WWW.WIPRO.COM


26
Example 2 on PreparedStatement
/* This class is executed in the following manner :
If you want to insert a row within the table, you will execute as
java JInsert jdbcdemotable 1001 anish admin 23-dec-2008 50000.00
*/
import java.sql.*;
class JInsert {
public static void main(String args[]){
try {
JdbcCalls e = new JdbcCalls();
e.insert(args);
}
catch(SQLException e) {
System.out.println(e.toString());
}
}
27
} 27
© 2015 WIPRO LTD | WWW.WIPRO.COM
Example 2 on PreparedStatement (Contd.).
class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void insert(String[] args) throws SQLException {
String tablename = args[0];
int empid = Integer.parseInt(args[1]);
String empname = args[2];
String dept = args[3];
String dat=args[4];
Float salary = Float.parseFloat(args[5]);

28 © 2015 WIPRO LTD | WWW.WIPRO.COM


28
Example 2 on PreparedStatement (Contd.).
PreparedStatement pst = con.prepareStatement("insert into
"+tablename+" values(?,?,?,?,?)");
pst.setInt(1, empid);
pst.setString(2, empname);
pst.setString(3, dept);
pst.setString(4, dat);
pst.setFloat(5, salary);
pst.executeUpdate();
System.out.println(“Record inserted successfully”);
}
}

29 © 2015 WIPRO LTD | WWW.WIPRO.COM


29
Example 2 on PreparedStatement (Contd.).

30 © 2015 WIPRO LTD | WWW.WIPRO.COM


30
Example 3 on PreparedStatement
/* This class is executed in the following manner :
If you want to display all the rows, you will execute as
java JDisplay jdbcdemotable
*/
import java.sql.*;
class JDisplay {
public static void main(String args[]) {
try {
JdbcCalls e = new JdbcCalls();
e.display(args);
}
catch(Exception e) {
System.out.println(e);
}
}
}
31 © 2015 WIPRO LTD | WWW.WIPRO.COM
31
Example 3 on PreparedStatement (Contd.).

class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}

Contd.. on next slide

32 © 2015 WIPRO LTD | WWW.WIPRO.COM


32
Example 3 on PreparedStatement (Contd.).

void display(String[] args) throws SQLException {


String tablename = args[0];
PreparedStatement pst = con.prepareStatement("select * from
"+tablename);
ResultSet rs= pst.executeQuery();
while(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3)+" "+rs.getDate(4)+" "+rs.getFloat(5));
}
con.close();
}
}

33 © 2015 WIPRO LTD | WWW.WIPRO.COM


33
Example 3 on PreparedStatement (Contd.).

34 © 2015 WIPRO LTD | WWW.WIPRO.COM


34
Example on Modifying the row
/* This class is executed in the following manner :
If you want to modify a row, you will execute as
java JModify table1 1001 60000.00
where modifying a row will allow you to change the salary
*/
import java.sql.*;
class JModify {
public static void main(String args[]) {
try {
JdbcCalls e = new JdbcCalls();
e.modify(args);
}
catch(SQLException e) {
System.out.println(e);
}
}
}
35 © 2015 WIPRO LTD | WWW.WIPRO.COM
35
Example on Modifying the row (Contd.).
class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void modify(String[] args) throws SQLException{
String tablename = args[0];
int empid = Integer.parseInt(args[1]);
Float sal = Float.parseFloat(args[2]);
PreparedStatement pst = con.prepareStatement("update "+tablename+"
set salary="+sal+" where empid="+empid);
int i= pst.executeUpdate();
con.close();
}
36
} 36
© 2015 WIPRO LTD | WWW.WIPRO.COM
Example on Deleting a row
/* This class is executed in the following manner :
If you want to delete a row, you will execute as
java JDelete table1 1001
*/
import java.sql.*;
class JDelete{
public static void main(String args[]) {
try {
JdbcCalls e = new JdbcCalls();
e.delete(args);
}
catch(SQLException e) {
System.out.println(e);
}
}
37
} © 2015 WIPRO LTD | WWW.WIPRO.COM
37
Example on Deleting a row (Contd.).
class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void delete(String[] args) throws SQLException {
String tablename = args[0];
int empid = Integer.parseInt(args[1]);
PreparedStatement pst = con.prepareStatement("delete from
"+tablename+" where empid="+empid);
int i= pst.executeUpdate();
con.close();
}
}
38 © 2015 WIPRO LTD | WWW.WIPRO.COM
38
Summary

In this module, you were able to:

– Analyze how to use the Metadata objects to retrieve


more information about the result set

– Create and execute a query using PreparedStatement


object

39 © 2015 WIPRO LTD | WWW.WIPRO.COM


39
Thank You

40 © 2015 WIPRO LTD | WWW.WIPRO.COM

You might also like