Monday, March 24, 2014
Today I  will show you "how to save objects to file" and "how to read objects from file". This is a very important thing which you may need while writing an application in Java. You might have an application where you would like to save the state of an object which you may require later. You can think of using databases, but it is very odd to use it for saving small number of objects. Also it may be that you dont have access to databases. So it is best to use the local file systemand save objects in files. This will make the application more light and have freater performance.
     This is very easy to do. Just as you write and read all other things from file, similarly this can be done. You have to do just these two things

  • The class whose object you want to save must  implement the interface java.io.Serializable. This interface is a tagging interface and has no abstract methods. As you knowobjects have existence only in JVM and they have no meaning in the external world. So making a class Serializable is quite like signing a contract with JVM that it can be taken outside it but it will be broken into bytes which will be actually saved in file. Similarly while reading the series of bytes from file will be read and the object will be reconstructed.
  • Wgile writing an object you need a stram to write it. The class java.io.ObjectOutputStream will help to write objects while java.io.ObjectInputStream will help to read objects.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class Student implements Serializable{
 private long roll;
 private String name;
 private static final long serialVersionUID = 1L;
 
 public Student(long roll, String name){
  this.roll = roll;
  this.name = name;
 }

 @Override
 public String toString() {
  return "Student [roll=" + roll + ", name=" + name + "]";
 }
}

class SerializableDemo{
 public static void main(String[] args) throws ClassNotFoundException, IOException {
     //creating instance of Student to save to file
  Student s = new Student(11004L,"Aditya Goyel");
  System.out.println("Before saving in file >>\n"+s);
  //creating the stream to write to file
  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("out.dat"));
  oos.writeObject(s);  //writing the object
  oos.close();  //closing the stream
  //creating the stream to read from file
  ObjectInputStream ois = new ObjectInputStream(new FileInputStream("out.dat"));
  Object o = ois.readObject();  //reading from file
  if(o instanceof Student)  //checking if it is a Student object
   o = (Student)o;  //type-cast to Student
  System.out.println("\nAfter reading from file >> \n"+o);
  ois.close();  //closing stream
 }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Before saving in file >>
Student [roll=11004, name=Aditya Goyel]

After reading from file >>
Student [roll=11004, name=Aditya Goyel]

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Sunday, March 23, 2014
This is a very popular question often asked in an interview. You also might be in a situation where you have to store the current date retrieved by java.util.Date in a database table where the datatype of the column is DATE . In that case you have to convert it to java.sql.Date . Also you might have to fetch date from database and then store it in a java.util.Date object . So this is a very important topic. Since both of these classes store the value of date in long milliseconds, so it is very easy to convert from one type to the other. Both of these classes have a method called getTime() which is used for conversion.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
public class DateConverter {

    public static void main(String[] args) {
      
        //creating instances of java.util.Date representing current date and time
        java.util.Date now = new java.util.Date();
        System.out.println("Value of java.util.Date : " + now);
      
        //converting java.util.Date to java.sql.Date in Java
        java.sql.Date sqlDate = new java.sql.Date(now.getTime());
        System.out.println("Converted value of java.sql.Date : " + sqlDate);
      
        //converting java.sql.Date to java.util.Date back
        java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
        System.out.println("Converted value of java.util.Date : " + utilDate);
    }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Value of java.util.Date : Sun Mar 23 11:35:46 IST 2014
Converted value of java.sql.Date : 2014-03-23
Converted value of java.util.Date : Sun Mar 23 11:35:46 IST 2014


Hope this helps. Happy coding :)
Friday, March 14, 2014
In our last post we discussed about how to obtain a database connection.After we have it, we can carry out different JDBC operations. Here we will discuss about

  • How to insert new records/rows in database tables (INSERT operation)
  • How to find a record/row in database tables (SELECT operation)
  • How to update records/rows in tables (UPDATE operation)
  • How to delete a record/row from tables (DELETE operation)
Different JDBC operations
SQL is written for carrying out the operations and it is either passed to a Statement or a PreparedStatement. The latter is used as DBMS has to only recompile and carry out the task. There is no need of parsing if PreparedStatement is used. Also it prevents SQL injection. You should use it everywhere when you have to pass parameters.  It is recommended to use in all public applications.

First create a database table Student as follows :
  CREATE TABLE student(id number primary key,name varchar(30));

-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentService {

 private Connection con;
 public StudentService(Connection con){
  this.con = con;  //database connection object
 }
 //Inserting new row in table with given id and name
 public void insertRecord(int id, String name) throws SQLException{
  con.setAutoCommit(false);
  String sql = "INSERT INTO student VALUES(?,?)";
  PreparedStatement ps = con.prepareStatement(sql);
  ps.setInt(1, id);
  ps.setString(2, name);
  ps.executeUpdate();
  con.commit();
  ps.close();
 }
 //Find a record based on id
 public void findRecord(int id) throws SQLException{
  String sql = "SELECT * FROM student WHERE id=?";
  PreparedStatement ps = con.prepareStatement(sql);
  ps.setInt(1, id);
  ResultSet rs = ps.executeQuery();
  if(rs.next())
   System.out.println(rs.getInt("id")+"\t"+rs.getString("name"));
  else
   System.out.println("No records found");
  ps.close();
 }
 //Find all the records
 public void findAllRecord() throws SQLException{
  con.setAutoCommit(false);
  String sql = "SELECT * FROM student";
  PreparedStatement ps = con.prepareStatement(sql);
  ResultSet rs = ps.executeQuery();
  while(rs.next())
   System.out.println(rs.getInt("id")+"\t"+rs.getString("name"));
  ps.close();
 }
 //Update a record with new name based on id
 public void updateRecord(int id, String name) throws SQLException{
  con.setAutoCommit(false);
  String sql = "SELECT id,name FROM student WHERE id=?";
  PreparedStatement ps=con.prepareStatement(sql,
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
  ps.setInt(1, id);
  ResultSet rs=ps.executeQuery();
  rs.updateString("name", name);
  rs.updateRow();
  con.commit();
  ps.close();
 }
 //Delete a record based on id
 public void deleteRecord(int id) throws SQLException{
  con.setAutoCommit(false);
  String sql = "DELETE FROM student WHERE id=?";
  PreparedStatement ps = con.prepareStatement(sql);
  ps.setInt(1, id);
  ps.executeUpdate();
  con.commit();
  ps.close();
 }
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Thursday, March 13, 2014
All those who are new to programming have dealt with data provided either from a file or command line. But you might ne in a situation where you have to store and access data from a persistent storage more easily and which is not a file, e.g. database. It fully depends on vendors and databse administrators how the data will be stored on the disk. It provides a much easier way to access and save data and coders dont have to think about storage. But before we go into saving and accessing data from a database, the first step is to create a connection with the databse from your java program. Here we will be using Oracle 11g Express edition as our database. We will use JDBC to obtain the connection.
JDBC Architecture

     Just as we need a device driver to use a hardwarte from a software, similarly we will need a driver to access the database. There are different types of drivers : type 1, type 2 , type 3 and type 4. For more about this visit Wikipedia JDBC driver . We will be using type 4 JDBC driver which is completely written in Java. If you have already installed Oracle you will find that in
C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar
Place that jar file in your classpath. Below is the code which will return the Connection object to the database
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public final class Provider {
 static{
  try {
   Class.forName("oracle.jdbc.OracleDriver");
   System.out.println("Driver loaded successfully");
  } catch (ClassNotFoundException e) {
   System.out.println("Failed to load driver");
  }
 }
 
 public static Connection getCon(String userid, String pass) throws SQLException{
  return DriverManager.getConnection(
    "jdbc:oracle:thin:@localhost:1521:xe", userid, pass);
 }
}


This is the fisrt and foremost step of using JDBC. Happy coding :)

Total Pageviews

Subscribe via Email

Followers


Popular Posts

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.