Saturday, 21 January 2017

MORE ON RESULTSETMETADATA

Statement or PreparedStatement provide the following method which is used to execute DDL, DML and DRL statements-
1. boolean execute(String sql) - Executes the given SQL statement, which may return multiple results.

  • UpdateCount--------Returns false
  • ResultSet------------Returns true
2. ResultSet getResultSet() - Retrieves the current result as a ResultSet object.

3. int getUpdateCount() - Retrieves the current result as an update count, if the result is a ResultSet object or there are no more results -1 is returned.


PROGRAM TO PERFORM ANY OPERATION


package Package1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Scanner;
public class Test30 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "rakesh");
Scanner scan = new Scanner(System.in);
System.out.println("Input query");
String query=scan.nextLine();
PreparedStatement ps = con.prepareStatement(query);
boolean b = ps.execute();
if(b==false)
{
int c=ps.getUpdateCount();
System.out.println(c+" row");
}
else if(b==true)
{
ResultSet rs = ps.getResultSet();
ResultSetMetaData rsmd = rs.getMetaData();
int count=rsmd.getColumnCount();
while(rs.next())
{
for(int i=1;i<=count;i++)
{
String type=rsmd.getColumnTypeName(i);
if(type.equals("NUMBER"))
System.out.println(rs.getInt(i)+" ");
if(type.equals("VARCHAR2"))
System.out.println(rs.getString(i)+" ");
if(type.equals("DATE"))
System.out.println(rs.getDate(i)+" ");
}
System.out.println();
}
}
}
}

Output -
Input query
update emp set sal=sal+300
14 row

Input query
delete from dept where deptno=69
1 row

No comments:

Post a Comment