0% found this document useful (0 votes)
15 views12 pages

Resultsetmetadata:: Date: 1-Mar-24

The document provides an overview of JDBC, focusing on ResultSetMetaData and PreparedStatement. It explains how to retrieve metadata about database columns and the advantages of using PreparedStatement to improve performance and prevent SQL injection attacks. Additionally, it includes code examples for inserting student records and images into a database using PreparedStatement.

Uploaded by

chaithu kasa11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views12 pages

Resultsetmetadata:: Date: 1-Mar-24

The document provides an overview of JDBC, focusing on ResultSetMetaData and PreparedStatement. It explains how to retrieve metadata about database columns and the advantages of using PreparedStatement to improve performance and prevent SQL injection attacks. Additionally, it includes code examples for inserting student records and images into a database using PreparedStatement.

Uploaded by

chaithu kasa11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Date: 1-Mar-24

ResultSetMetaData:
 MetaData --- Data about Data
 In a Java program you write comments, they represent
metadata.
 In a Java program you write annotations, they represent
metadata.

 ResultSetMetaData is used to get the information about the


columns which are stored in ResultSet object.

 ResultSetMetaData is an interface, its implementation will be


available in driver software.

 For the interfaces provided in JDBC API, the implementations


exist in Driver software/application.

 Call getMetaData() method of ResultSet


object, to create ResultSetMetaData object.

 ResultSetMetaData rsmd = rs.getMetaData();

 To extract the information about the columns


from the ResultSetMetaData object, we have
to call the below methods.

 1. getColumnCount() : returns the number of columns in


ResultSet object.
 2. getColumnTypeName(columnIndex) : returns
the datatype of the column in ResultSet
object.

 3. getColumnDisplaySize(columnIndex) :
returns the size of the column in ResultSet
object.

 4. isNullable(columnIndex) : returns true,


if the column allows null, otherwise returns
false.

ResultSet rs = stmt.executeQuery( "SELECT EMPNO,


SAL, ENAME FROM EMP ");
ResultSetMetaData rsmd =
rs.getMetaData();
int columns_count =
rsmd.getColumnCount();
for(int index = 1; index <=
columns_count; index++ ) {
System.out.println("column number
: " + index);
System.out.println("column name
: " + rsmd.getColumnName(index));
System.out.println("column type
: " + rsmd.getColumnTypeName(index));
System.out.println("column size
: " + rsmd.getColumnDisplaySize(index));
System.out.println("isNullable
: " + rsmd.isNullable(index));
System.out.println("============================
============");
} //end for

Types of statements in JDBC:

1. Statement
2. PreparedStatement
3. CallableStatement

Statement
<<interface>>

PreparedStatement
<<interface>>

CallableStatement
<<interface>>

 PreparedStatement is an extension of
Statement.
 CallableStatement is an extension of
PreparedStatement.

Statement stmt = conn.createStatement();

//insert records of 500 students

1. Create a for loop which repeats from 1 to


500
2. Take the student data from user within
the loop
3. Put the data/values in the insert query
4. Call executeUpdate() method with query to
insert the student record.

Scanner sc = new Scanner(System.in);


for(int i = 1; i <= 500; i++) {

S.o.p(“enter student id”);


int sid = sc.nextInt();

//similarly for other data

String query = “ INSERT INTO STUDENT


VALUES( “ + sid + “ , ‘ “ +
sname +
“ ‘ , “ + marks + “ )
“;
int k = stmt.executeUpdate(query);
}

 In the above code, each time when the query


is sent to the database, it is compiled
first then
Executed next then the result will be
returned back to the program.
 Here, the loop repeats for 500 times, so the
same query will be compiled for 500 times.
 The problem with this kind of execution is
it decreases the performance of a program.
 The solution for the above problem is, use
PreparedStatement interface.
 PrepardStatemt allows us to pre-compile SQL
query for once and you can execute the query
as many times you want without compilation
again.
 So PreparedStatement improves the
performance of an application.
 PreparedStatement is given for three
reasons.
1. To improve the performance
2. To prevent SQL Injection attacks.
3. To store/retrieve the images

How to create PreparedStatement?

PreparedStatement pstmt =
conn.prepareStatement(query);

 Here, query is passed to compile and to


execute. So we have put placeholders(?) for
parameters.
 Ex:
String query = “INSERT INTO STUDENT
VALUES(?, ?, ?)”;
PreparedStatement pstmt =
conn.prepareStatement(query);
 Whenever we are working with the
PreparedStatement, there are 3 steps to
follow.
 1. Preparing
 2. Parameter setting
 3. Executing the query
 Preparing is nothing but creating the
PreparedStatement object.
 Call setXxx() methods to set the values to
the parameters
 Call executeUpdate() / executeQuery()
methods

Example:
package com.ashokit.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class Pstmt_Example {

public static void main(String[] args) {

String databaseURL =
"jdbc:oracle:thin:@localhost:1521:xe";
String uname = "system";
String pwd = "tiger";

Connection conn = null;


PreparedStatement pstmt = null;
try {
conn =
DriverManager.getConnection(databaseURL, uname,
pwd);
String query = "INSERT INTO STUDENT
VALUES( ?, ?, ?)";
pstmt = conn.prepareStatement(query);

Scanner sc = new Scanner(System.in);


for (int i = 1; i <= 5; i++) {

System.out.println("Please enter
student id");
int sid = sc.nextInt();
pstmt.setInt(1, sid);

sc.nextLine();

System.out.println("Please enter
student name");
String sname = sc.nextLine();
pstmt.setString(2, sname);
System.out.println("Please enter
student marks");
int marks = sc.nextInt();
pstmt.setInt(3, marks);

pstmt.executeUpdate();
System.out.println("Row
inserted ......");

} // end for
} // end try
catch (Exception ex) {
ex.printStackTrace();
} // end catch
finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} //end finally

} //end main

} //end class

 SQL Injection attack?


---------------------
For ex:
S.o.p(“enter username”);
String username = sc.nextLine();
String query = “SELECT * FROM USERS WHERE
USERNAME = “+ username;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

The malicious user has entered the username


as
‘Sathish’ OR 1=1

If the username is substituted in the query


then it becomes,
SELECT * FROM USERS WHERE USERNAME =
‘Sathish’ OR 1=1

 In the above query, the malicious


user/hacker don’t know the username but 1=1
is always true. So the hacker is able to
steal the data of all the users.
 This type of SQL Injection attacks are
possible with Statement object.
 To prevent SQL injection attacks, we have to
use PreparedStatement object.
For ex:
 S.o.p(“enter username”);
 String username = sc.nextLine();
 String query = “SELECT * FROM USERS WHERE
 USERNAME = ? “;
PreparedStatement pstmt =
conn.prepareStatement(query);
Suppose, a hacker has given username as
‘sathish’ or 1=1
pstmt.setString(1, username);
Now the query is
“SELECT * FROM USERS WHERE USERNAME =
‘sathish’ or 1=1 “

 In this case, there is no user with the


given username, so hacker can’t steal the
data of the users.

Storing an image in a database:


-------------------------------
 To store an image in a database, the table
must contain a column of datatype BLOB.
 BLOB – Binary Large Object
 The image type that can be stored in a
database, is except bmp files.
 package com.ashokit.jdbc;

 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.SQLException;

 public class Insert_Image {

 public static void main(String[] args) {

 String databaseURL =
"jdbc:oracle:thin:@localhost:1521:xe";
 String uname = "system";
 String pwd = "tiger";

 Connection conn = null;
 PreparedStatement pstmt = null;
 try {
 conn =
DriverManager.getConnection(databaseURL,
uname, pwd);
 String query = "INSERT INTO
IMAGES VALUES(?, ?)";
 pstmt =
conn.prepareStatement(query);
 pstmt.setString(1, "earth");

 File file = new File("C:\\Users\\
hi\\Documents\\planet.jpg");

 FileInputStream fis = new
FileInputStream(file);
 //pstmt.setBinaryStream(2, fis);
 pstmt.setBlob(2, fis);

 pstmt.executeUpdate();
 System.out.println("Row
inserted.....");
 }catch(SQLException | IOException ex)
{
 ex.printStackTrace();
 }
 finally {
 try {
 if (pstmt != null) {
 pstmt.close();
 }

 if(conn != null) {
 conn.close();
 }
 }catch(Exception e) {
 e.printStackTrace();
 }
 }

 }

 }

You might also like