Tuesday, October 30, 2018

program to write a picture into BLOB column

// program to write a picture into BLOB column


/* -------------------------------------------------------------------------------
create table players
( name varchar2(20),
photo blob
);
--------------------------------------------------------------------------------- */

// call program by passing name of the player and image file as parameters.
// Example : java BLOBWrite zidane zidane.jpg

import java.sql.*;
import java.io.*;

public class BLOBWrite
{
public static void main(String args[])
{

try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");

// connect using OCI driver assuming program runs on the same machine as Oracle9i
Connection con = DriverManager.getConnection("jdbc:oracle:oci8:@","sri","sri");
con.setAutoCommit(false);


PreparedStatement ps = con.prepareStatement("insert into players values(?,?)");

File picfile = new File(args[1]);
FileInputStream is = new FileInputStream(picfile);

ps.setString(1,args[0]);
ps.setBinaryStream(2,is,(int) picfile.length());

ps.executeUpdate();

con.commit();

ps.close();
con.close();

}
catch(Exception ex)
{
ex.printStackTrace();
}

} // end of main

} // end of BLOBWrite

Friday, October 19, 2018

How to run a simple program in Bean

 

How to run a simple program in Bean



https://code.google.com/archive/p/jbaindi/downloads?page=3


Thursday, October 18, 2018

My Favourites

 


My Favourites

Here are books, videos and websites that I personally liked a lot and strongly recommend.

Websites

The following are websites that I like and use to enhance my knowledge.

https://www.w3schools.com/Provides simple and precise tutorials covering HTML, CSS, JavaScript, SQL and many others.
https://www.khanacademy.orgProvides a lot of videos to learn Maths, Physics, Finance, Programming and many more.
https://www.stackoverflow.comIf you can't find solution to your technical problem elsewhere, do search in stackoverflow to get answers.
https://www.tutorialspoint.comLots of tutorials that are easy to follow as they are precise and concise.
https://www.udemy.comHosts a lot of video courses covering a lot of technical and non-technical topics. Some courses are free and some are to be purchased.

Here are my courses in Udemy.com: [C Language For Beginners]   [C Language Interview Questions]
https://www.udacity.comProvides a lot of video courses covering all advanced topics like AI, Data Science, Programming and many more.
https://www.coursera.comThis provides video courses created by various top universities like Stanford, Yale University, Johns Hopkins, National University of Singapore.

Books

The following are books I enjoyed reading.

  • The Outliers - Malcolm Gladwell
  • Factfulness - Hans Rosling
  • Bad Blood - John Carreyrou
  • Thank you for being late - Thomas L. Friedman
  • Shoe Dog - Phil Knight
  • Long walk to freedom - Nelson Mandela
  • You can win - Shiv Khera
  • The Monk who sold his Ferrari - Robin Sharma
  • To kill a mockingbird - Harper Lee

Inspirational Videos

These are some of the videos that I found quite inspirational.

XPath using JAXP

 import java.util.Scanner;

import javax.xml.xpath.*;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XPathDemo {
    
    public static void main(String[] args) {
        //  associate Scanner with keyboard
        Scanner s = new Scanner(System.in); 
        try 
        {
         XPathFactory x = XPathFactory.newInstance();
         XPath path = x.newXPath();
         while ( true )
         {
          // take xpath expression from user
          System.out.println("Enter XPATH expression : ");
          String expression = s.nextLine();
          if ( expression.length() == 0 ) 
               break;
          // read content from  team.xml from c:\xml folder. Change it accordingly
          InputSource source = new InputSource("c:\\xml\\team.xml");
          try 
          {
           // search source using xpath expression
           NodeList nl = (NodeList) path.evaluate( expression, source, XPathConstants.NODESET); 
           
           // display selected nodes
           for ( int i = 0 ; i < nl.getLength(); i ++)
              System.out.printf("%s : %s\n", nl.item(i).getNodeName(), nl.item(i).getTextContent());
          }
          catch(Exception ex) {
             System.out.println("Invalid XPath Expression");
          }
         } // end of while 
        }
        catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Creating Authors.xml from Table


 // program to create authors.xml from AUTHORS table

    import javax.xml.parsers.*;
    import java.io.*;
    import org.w3c.dom.*;

    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;

    import java.sql.*;

    public class CreateAuthors {

    public static void main(String[] argv)  throws Exception
    {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document  document;

    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.newDocument();

    // connect to database
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:authors","Admin","");
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery("select * from authors");

    Element authors,author,ele;
    authors  = document.createElement("authors");
    document.appendChild(authors);

    while ( rs.next())
    {
    author = document.createElement("author");
    ele = document.createElement("au_id");
    ele.appendChild(document.createTextNode(rs.getString("au_id")));
    author.appendChild(ele);

    ele = document.createElement("author");
    ele.appendChild(document.createTextNode(rs.getString("author")));
    author.appendChild(ele);

    ele = document.createElement("yearborn");
    ele.appendChild(document.createTextNode(rs.getString("yearborn")));
    author.appendChild(ele);

    authors.appendChild(author);
    }
    rs.close();
    st.close();
    con.close();

    FileWriter fw = new FileWriter("authors.xml");

    // Use a Transformer for output
    TransformerFactory tFactory =  TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(fw);
    transformer.transform(source, result);
    } // main 

    } 

3-Tier Application Using RMI



3-Tier Application Using RMI

Here I am providing a 3-tier client/server application using Oracle as the database, RMI remote object as application tier and a swing frame or a console application as the client.

This application is built with NetBeans IDE 5.5. You can download both server and client projects using the links below.

Server project (empserver) - empServer.zip    empserver.zip
Client project (empclient)- empclient.zip    empclient.zip

Steps related to empserver  (server ) project.

  1. First make sure you downloaded empserver.zip
  2. Unzip empserver into any directory. It will create a directory with the name empserver
  3. Start NetBeans IDE 5.5 and open the project by selecting empserver  as the folder
  4. This project needs to have Oracle JDBC driver, which is in OJDBC14.jar file. So include that in empserver project using libraries node in project window. This application is using  Oracle10g XE (Express Edition). In case you are using some other Oracle version, please change connection process accordingly in Database.java file.  In this case, you may also have to change the table name and column names in EmpImpl.java.
  5. Build the project.
  6. Class files related to .java files are placed in   build/classes directory of empserver project.
  7. Go to command prompt. Go to directory build/classes in empsever project directory.
  8. Run RMIC command as shown below from  build/classes directory
    RMIC  employee.EmpImpl
  9. Run RMIRegistry from the build/classes directory as follows
    RMIRegistry
  10. Come to NetBeans IDE 5.5 and  run EmpImpl.java. Make sure it is displaying a messaging saying "Employee Server Ready".
  11. The following are the files related to empserver project:
    • EmployeeTO.java  -  This is Employee class using Transfer Object design pattern
    • EmployeeNotFoundException.java - User-defined exception for employee not found
    • Database.java   -  A class to connect to database. Whenever a change in database is required, only this class is to be modified.
    • Emp.java  - Remote interface
    • EmpImpl.java  - Implementation class

Steps related to client:

  1. First make sure you downloaded empclient.zip
  2. Unzip empclient into any directory. It will create a directory with the name empclient
  3. Open the project by selecting empclient  as the folder
  4. Go to libraries node in Project window and select  Add Jar/Folder option.
  5. From the dialog box, select   empserver/build/classes directory as the directory to be included in client project. This steps is required as some components required by client are placed in employee package which is in build/classes folder of empserver.
  6. Build the project.  
  7. Run EmpClient.java.  It should display details of  employee with id 100.
  8. Run EmpSwingClient.java  It provides textfield to enter employee id. Enter 100 and then click on Get Details button. Once details are obtained, change salary in second textfield and click on update button. You can check whether salary is changed or not by click on Get Details button to get details of employee id 100 again. 
  9. File related to empclient projects are :
    • EmpClient.java  - Console client.
    • EmpSwingClient.java  - Client based on Swing Frame.
    • The following is the snapshot of Swing Client.








Good Luck

Using JoinRowSet to join Employees and Jobs tables

 



import oracle.jdbc.rowset.*;
import javax.sql.rowset.*;

public class JoinRowSetDemo {

    public static void main(String[] args) throws Exception {

        CachedRowSet crs1 = new OracleCachedRowSet();
        crs1.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
        crs1.setUsername("hr");
        crs1.setPassword("hr");
        crs1.setCommand("select job_id,job_title from jobs");
        crs1.execute();

        CachedRowSet crs2 = new OracleCachedRowSet();
        crs2.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
        crs2.setUsername("hr");
        crs2.setPassword("hr");
        crs2.setCommand("select job_id,first_name, salary from employees");
        crs2.execute();

        JoinRowSet jrs = new OracleJoinRowSet();
        jrs.addRowSet(crs1,"job_id");   // join column
        jrs.addRowSet(crs2,"job_id");   // join column

        // get values using column number. 1. for job_id, 2. job_title, 3.first_name, 4. salary
        
        while (jrs.next()) {
            if  ( jrs.getInt(4) > 10000)  // salary > 10000
               System.out.printf("Employee [%s]  is [%s]\n", jrs.getString(3), jrs.getString(2));
        }

    }
}

Using FilteredRowSet to filter Jobs

 


import java.sql.*; 
import javax.sql.*;
import oracle.jdbc.rowset.*;

public class FilteredRowSetDemo {
    
    public static void main(String[] args) throws Exception{
        OracleFilteredRowSet rs = new OracleFilteredRowSet();
        rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
        rs.setUsername("hr");
        rs.setPassword("hr");
        rs.setCommand("select * from jobs");
        rs.setFilter( new PredicateImpl());
        rs.execute();
        while ( rs.next() ) {
              System.out.println( rs.getString("job_title") + ":" + rs.getString("min_salary"));
        }
        rs.close();
         
    }
}

class  PredicateImpl implements OraclePredicate
{
    public boolean evaluate(RowSet rs) {
        try {
          int minsal = rs.getInt(3);
          if ( minsal > 5000)
            return true;
          else
              return false;
        }
        catch(Exception ex) {
           return false;
       }
    }
    public boolean evaluate(Object object, int i) throws SQLException {
        return true;
    }

    public boolean evaluate(Object object, String string) throws SQLException {
        return true;
    }
}

program to display a picture taken from BLOB in a Framebased application



/* -------------------------------------------------------------------------------
create table players
( name varchar2(20),
photo blob
);
------------------------------------------------------------------------------- */

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.io.*;

public class DisplayBLOB extends JFrame implements ActionListener
{
Connection con;
Statement st;
ResultSet rs;

JLabel lblimage = new JLabel();
JLabel lblname = new JLabel();

JButton btnNext,btnPrev;

public static void main(String args[])
{
new DisplayBLOB();
}

public ResultSet getResultSet() throws Exception
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");

// connect using OCI driver assuming program runs on the same machine as Oracle9i
con = DriverManager.getConnection("jdbc:oracle:oci8:@","sri","sri");
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select name,photo from players");
rs.next();
return rs;
}

class WinCode extends WindowAdapter
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
}

public DisplayBLOB()
{

super("Players");
this.addWindowListener(new WinCode());

try
{
rs = getResultSet();
// create buttons
btnNext = new JButton("Next");
btnPrev = new JButton("Prev");

btnNext.addActionListener(this);
btnPrev.addActionListener(this);

JPanel p = new JPanel();
p.setLayout( new FlowLayout());
p.add(btnPrev);
p.add(btnNext);


Container c = getContentPane();

lblname.setHorizontalAlignment(SwingConstants.CENTER);
lblimage.setHorizontalAlignment(SwingConstants.CENTER);

c.add(lblname,"North");
c.add(lblimage,"Center");

c.add(p,"South");

setSize(400,400);
setVisible(true);

displayPlayer();

}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}

public void displayPlayer() throws Exception
{

// display details of a player from current row in ResultSet

lblname.setText(rs.getString(1));
Blob photo = rs.getBlob(2);

byte b[] = new byte[(int) photo.length()];

InputStream is = photo.getBinaryStream();

is.read(b);

Toolkit tk = Toolkit.getDefaultToolkit();
Image image = tk.createImage(b); // create an image from array of bytes
Icon img = new ImageIcon(image);
lblimage.setIcon(img);

}


public void actionPerformed(ActionEvent evt)
{
try
{

if (evt.getSource() == btnNext)
{
if (!rs.isLast()) // if not at the last row in resultset
rs.next();
}
else
{
if ( ! rs.isFirst()) // if not at the first row in resultset
rs.previous();
}

displayPlayer();

}
catch(Exception ex)
{
System.out.println( ex.getMessage());
}
}

} // end of DisplayBlob 

derby Lab JDBC


Steps to add derby.jar in intelliJ


Derby.jar

Add jar file in “lib” folder

“derby-10.13.1. jar”

Configure of Database

Goto “File”  Menu

Goto “ Project Structure”

Goto “ Project Settings” -> Select “ Modules”

Then Select “Dependencies” Tab

Then Click on ( + ) on right side to add “ Jar or directories” Option & “derby.jar”

Apply -| Click on Ok.





1.  CreateTable.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class CreateTable {

   
public static void main(String[] args) throws Exception {

        Connection con = DriverManager.getConnection(
"jdbc:derby:D:\\Notes\\TU\\bca 6 th sem\\db\\testdb;create=true");
       
//System.out.println("Connected to Derby Database!");
       
Statement st = con.createStatement();
        st.executeUpdate(
"create table publishers( publisher_id char(6),name char(30), url char(80) )");
        System.out.println(
"table created");
        st.close();
        con.close();


    }

}

 

2.  AddTable.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class AddTable {

   
public static void main(String[] args) throws Exception {

        Connection con = DriverManager.getConnection(
"jdbc:derby:D:\\Notes\\TU\\bca 6 th sem\\db\\testdb;create=true");
       
//System.out.println("Connected to Derby Database!");

       
PreparedStatement ps = con.prepareStatement("insert into Publishers(publisher_id, name, url) values (?,?,?)");
        ps.setString(
1, "0201");
        ps.setString(
2, "Addison-wesleey");
        ps.setString(
3, "www.aw-bc.com");

        ps.executeUpdate();
        ps.close();


        System.
out.println("table inserted");

        con.close();


    }

}

 

3.  ListTablePublishers.java

 

import java.sql.Connection;
import java.sql.DriverManager;

import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;

public class ListTablePublishers {

   
public static void main(String[] args)  throws Exception{
       
// TODO Auto-generated method stub

       
RowSetFactory factory = RowSetProvider.newFactory();
        CachedRowSet crs = factory.createCachedRowSet();

        String url =
"jdbc:derby:D:\\Notes\\TU\\bca 6 th sem\\db\\testdb";
        crs.setUrl(url);
        crs.setCommand(
"select * from Publishers");
        crs.execute();
       
while(crs.next())
            System.
out.println(crs.getString("url"));

        crs.close();


    }

}

 

 

4.  TestConnection.java

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

 

public class TestConnection {

 

       public static void main(String[] args) throws SQLException {

             

              Connection conn = DriverManager.getConnection("jdbc:derby:D:\\Notes\\TU\\bca 6 th sem\\db\\testdb;create=true");

              System.out.println("Connected to Derby Database!");

             

              Statement stmt = conn.createStatement();

            

              //Creating a table in Derby database

             String query = "CREATE TABLE Books( "

                + "Title CHAR(60), "

                + "ISBN CHAR(13), "

                + "Publisher_Id CHAR(6), "

                + "Price DECIMAL(10,2))";

             stmt.execute(query);

             stmt.close();

          

             System.out.println("Table created");    

              conn.close();

       }

 

}

 

5.  CreateGreatingTable.java

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateGreatingTable {

   
public static void main(String[] args) throws SQLException {
       
// TODO Auto-generated method stub
       
Connection conn = DriverManager.getConnection("jdbc:derby:D:\\Notes\\TU\\bca 6 th sem\\db\\testdb;create=true");
        System.
out.println("Connected to Derby Database!");


        Statement stmt = conn.createStatement();
       
//Creating a table in Derby database
     
     
     
String query = "CREATE TABLE Greetings(Message CHAR(20))";
         stmt.execute(query);
        
          query =
"INSERT INTO Greetings VALUES('Hello, World')";
            stmt.execute(query);
         stmt.close();
         System.
out.println("Table created");
      
      
        ResultSet rs = stmt.executeQuery(
"Select * from Greetings");
        System.
out.println("Contents of the table Greetings table:");
       
while(rs.next()) {
            System.
out.print(rs.getString("Message"));
            System.
out.println();
        }

        conn.close();
    }

}

 


Wednesday, October 17, 2018

Java Server Pages (JSP) Displaying table data using pagination

 

Java Server Pages (JSP)


//Displaying list of employees for the given department 

<%@ page import="java.sql.*"%>

<%
  int PAGESIZE = 5;
  
  String spageno = request.getParameter("pageno");
  int pageno, nopages;
  
  
  if ( spageno == null)
     pageno=1;
  else
     pageno = Integer.parseInt(spageno);
     

  // connect using Thin driver
  Class.forName("oracle.jdbc.driver.OracleDriver"); 
  Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oracle8i","scott","tiger");
  Statement st = con.createStatement();
  ResultSet rs = st.executeQuery("select * from emp");
  
  // skip rows based on page number and also find out no. of rows 
  int srow = (pageno - 1) * PAGESIZE;
  
%>

<h2>Employees List </h2>
<table border=1>
<tr><th>Empno<th>Name <th>Salary
</tr>

<%
  int nrows = 0 ;
  while ( rs.next())
  {
     if ( nrows >= srow  &&  nrows  < srow + PAGESIZE)
         out.println( "<tr><td>" + rs.getString("empno") + "<td>" + rs.getString("ename") + "<td>" +  rs.getString("sal") + "</tr>" );
         
     nrows++;
  }
  
  rs.close();
  st.close();
  con.close();
    
  // convert double to int using ceil() function
  nopages = (int) Math.ceil(nrows / (double) PAGESIZE);
  
  // display page no.with hyper links
  out.println("<tr> <td colspan=3>");
  
  for ( int i = 1; i <= nopages ;i ++)
    if ( i != pageno )
      out.println("<a href=emplist.jsp?pageno=" + i + ">" +  i + "</a>&nbsp;");
    else
      out.println(i + "&nbsp;");
  
  out.println("</tr></table>");


%>


How to embed Apache Derby Database E in your JAVA Application


 

Tuesday, October 16, 2018

Compile error: package javax.servlet does not exist

 Copy the file "servlet-api.jar" from location YOUR_INSTILLATION_PATH\tomcat\lib\servlet-api.jar and Paste the file into your Java Directory YOUR_INSTILLATION_PATH\Java\jdk1.8.0_121\jre\lib\ext

this will work (tested).

Working with Embedded Java Databases & IntelliJ Idea | The perfect Java Developer setup


 

Thursday, October 11, 2018

Lab JDBC Last

Displaying information about database using DatabaseMetadata

  // Program to display information about the database

    import java.sql.*;
    public class DBMetaData
    {
     public static void main(String args[])
     {
      try {
       // load oracle driver
       Class.forName("oracle.jdbc.driver.OracleDriver"); 
       // connect using Thin driver
       Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
                       "scott","tiger");
       // get metadata
       DatabaseMetaData  dbmd = con.getMetaData();
       System.out.println("Product Name: " + dbmd.getDatabaseProductName());
       System.out.println("Product Version: " + dbmd.getDatabaseProductVersion());
       // Display list of available users (schemas)
       System.out.println("List of users of the database");
       ResultSet  s =  dbmd.getSchemas();
       while ( s.next())
            System.out.println(s.getString(1));
       /* list of table of the user Scott */
       System.out.println("List of Table of user  SCOTT");
       /*  getTables(catalog, schema,tablename,tabletype)  */
       ResultSet  tlist = dbmd.getTables(null,"SCOTT","%",null);
       // display name of all tables
       while (tlist.next())
       {
        System.out.println( tlist.getString("TABLE_NAME"));
       }
     }// end of try
     catch(Exception ex)
     {
	   System.out.println("Error : " +  ex);
     }
  } // end of main
} // end of class 

Reading CLOB from a column of a table

// program to read data from CLOB column

/* -------------------------------------------------------------------------------
   create table lobs
   ( id number(2),
     resume  clob
   );
--------------------------------------------------------------------------------- */

// This program assumes you have created a table given above and inserted a row with 
// ID 1 and some value for CLOB


import  java.sql.*;
import  java.io.*;

public class CLOBRead
{
 public static void main(String args[])
 {

  try
  {
   // load oracle driver
  Class.forName("oracle.jdbc.driver.OracleDriver"); 

  // connect using OCI driver assuming program runs on the same machine as Oracle9i
  Connection con =   DriverManager.getConnection("jdbc:oracle:oci8:@","sri","sri");

  Statement st = con.createStatement();
  ResultSet rs = st.executeQuery("select * from lobs where id = 1");
  rs.next();
 
  Clob clob = rs.getClob(2);   // get lob from second column

  InputStream is = clob.getAsciiStream();   // get stream to read data from lob
  int ch;
  while(  (ch=is.read()) != -1)
     System.out.print( (char) ch);

  rs.close();
  st.close();
  con.close();

  }
  catch(Exception ex)
  {
    ex.printStackTrace();
  }

 } // end of main

} // end of CLOBRead


Executes given query and displays result in JTable

/*
     Program to take an SQL command from user and execute it.
     Uses TableModel to display data in a table.
     */
     import javax.swing.*;
     import javax.swing.table.*;
     import java.awt.*;
     import java.awt.event.*;
     import java.sql.*;
     
     public class  Query extends JFrame implements ActionListener
     {
     JTable  table;
     JTextField  tfquery;
     JButton btn;
     
      public static void main(String args[])
      {
        new Query();
      }

      public  Query()
      {
      super("Query");
      tfquery = new JTextField(30);
      btn= new JButton("Execute");
      table = new JTable();
      JScrollPane sp = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      Container c = getContentPane();
      JPanel tp  = new JPanel( new FlowLayout());
      tp.add(tfquery);
      tp.add(btn);
      btn.addActionListener(this);

      c.add(tp,"North");
      c.add(sp);

      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
      setSize(500,300);
      setVisible(true);
      }

      public void actionPerformed(ActionEvent evt)
      {

      table.setModel( new TableData( tfquery.getText()));
      table.createDefaultColumnsFromModel();
      }

      }

      class TableData extends AbstractTableModel
      {
      Connection con;
      Statement st;
      ResultSet  rs;
      ResultSetMetaData rsmd;
      int nrows;
      public TableData(String query)
      {
      try
      {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oracle10",
      "scott","tiger");
      st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      rs = st.executeQuery(query);
      rsmd = rs.getMetaData();
      // get row count
      nrows = 0;
      while ( rs.next())
      {
      nrows ++;
      }
      rs.beforeFirst();
      }
      catch(Exception ex) { System.out.println( ex.getMessage()); }
      }

      public Object getValueAt(int row, int column)
      {
      try
      {
      rs.absolute(row+1);
      return rs.getString(column+1);
      }
      catch ( Exception ex){ System.out.println(ex.getMessage());}
      return null;
      }

      public int getColumnCount()
      {
      try
      {
      return rsmd.getColumnCount();
      }
      catch ( Exception ex) {}
      return 0;
      }

      public int getRowCount()
      {
      return nrows;
      }

      public String getColumnName(int index)
      {

      try
      {
      return  rsmd.getColumnName(index+1);
      }
      catch (Exception ex){ System.out.println(ex.getMessage()); }
      return null;
      }

      public Class  getColumnClass( int index)
      {
      return String.class;
      }
    }

Calling a Stored Function using CallableStatement


/*
     Program to call a function using callable statement.
     
     Make sure stored function GETEMPCOUNT is already created
     in Oracle database before you run this program.

     */
     import  java.sql.*;

     public class EmpCount
     {

     public static void main(String args[])
     {
      if ( args.length < 1 )
      {
      System.out.println("EmpCount   deptno");
      System.exit(1);
      }
      try
      {
      // load oracle thin driver
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
      "scott","tiger");
      // create a callable statement
      CallableStatement cs = con.prepareCall("{?=call GetEmpCount(?)}");
      // specify the return type
      cs.registerOutParameter(1,Types.INTEGER);
      cs.setInt(2, Integer.parseInt( args[0]));
      // execute EMPCOUNT function
      cs.execute();
      // display the return value of the function
      System.out.println("No.of Employees : " + cs.getInt(1));
      cs.close();
      con.close();
     }
     catch(Exception ex)
     {
      System.out.println("Error : " +  ex);
     }
    } // end of main
   } // end of  TestConnection
jhk


CORBA Java Tutorial using Netbeans and Java 8.

CORBA-Example A simple CORBA implementation using Java Echo.idl module EchoApp{ interface Echo{ string echoString(); }; }; ...