Home Java Example Java Io Insert Serialized Object into Database Table
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Insert Serialized Object into Database Table

Advertisement
In this section, you will learn how to Insert a serialized object into database table, deserialize it after fetching it from database table and displaying it on console.

Insert Serialized Object into Database Table

In the previous tutorial, you have learned about Serializing and Deserializing an object and inserting it into a file. In this section, you will learn how to Insert a serialized object into database table, deserialize it after fetching it from database table and displaying it on console.

EXAMPLE

In the below example, we are going to Serialize StudentDetails class and inserting it into a database table serializationtest using class InsertSerialObject. The database name is ankdb.

The Create query for serializationtest database table is given below :

create table serializationtest(name blob,viewname varchar(30))

The code of InsertSerialObject class is given below :

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertSerialObject {
static String userid = "root", password = "root";
static String url = "jdbc:mysql://192.168.10.13:3306/ankdb";
static int count = 0;
static Connection con = null;

public static void main(String[] args) {
Connection con = getMySQLJDBCConnection();
StudentDetails student1 = new StudentDetails("Kapil", 26, "Male");
StudentDetails student2 = new StudentDetails("Nitesh", 26, "Male");
StudentDetails student3 = new StudentDetails("Divya", 26, "Female");
PreparedStatement ps;
try {
ps = con
.prepareStatement("INSERT INTO serializationtest VALUES (?, ?)");
write(student1, ps);
ps.execute();
write(student2, ps);
ps.execute();
write(student3, ps);
ps.execute();
ps.close();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM serializationtest");
while (rs.next()) {
Object obj = read(rs, "Name");
StudentDetails p = (StudentDetails) obj;
System.out.println(p.name + "\t" + p.age + "\t" + p.sex);
}
rs.close();
st.close();
} catch (Exception e) {
}
}

public static void write(Object obj, PreparedStatement ps)
throws SQLException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(baos);
oout.writeObject(obj);
oout.close();
ps.setBytes(1, baos.toByteArray());
ps.setInt(2, ++count);
}

public static Object read(ResultSet rs, String column) throws SQLException,
IOException, ClassNotFoundException {
byte[] buf = rs.getBytes(column);
if (buf != null) {
ObjectInputStream objectIn = new ObjectInputStream(
new ByteArrayInputStream(buf));
return objectIn.readObject();
}
return null;
}

public static Connection getMySQLJDBCConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, userid, password);
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
return con;
}
}

OUTPUT

When code executes, it insert three objects student1, student2, student3 into database table serializationtest and produce the following output on console after desterilizing the these 3 objects :

Kapil 26 Male
Nitesh 26 Male                         
Divya 26 Female

Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 2, 2011

Ask Questions?    Discuss: Insert Serialized Object into Database Table  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
newbProgrammer
May 1, 2012
StudentDetails class

Could you add a StudentDetails class or describe it atleast
Moulika Thirumalasetty
April 10, 2013
Serialized object stored into database

I am not getting the output while executing the below code..Could anyone tell please????It is not giving any errors but data is not inserted into database.... import java.io.*; public class Studentdetails implements Serializable { String name; String age; String sex;} import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class InsertSerialObject { public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","SYSTEM","admin"); Studentdetails s1 = new Studentdetails(); s1.name="moulika"; s1.age="22"; s1.sex="female"; PreparedStatement ps; try { ps = con .prepareStatement("INSERT INTO serializationtest VALUES (?,?,?)"); write(s1, ps); System.out.println("inserted"); ps.close(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM serializationtest"); while (rs.next()) { Object obj = read(rs, "name"); Studentdetails p = (Studentdetails) obj; System.out.println(p.name + "\t" + p.age + "\t" + p.sex); } rs.close(); st.close(); } catch (Exception e) { } } public static void write(Object obj, PreparedStatement ps) throws SQLException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(baos); oout.writeObject(obj); oout.close(); ps.setBytes(1, baos.toByteArray()); int count=0; ps.setInt(2, ++count); } public static Object read(ResultSet rs, String column) throws SQLException, IOException, ClassNotFoundException { byte[] buf = rs.getBytes(column); if (buf != null) { ObjectInputStream objectIn = new ObjectInputStream( new ByteArrayInputStream(buf)); return objectIn.readObject(); } return null; } }
Moulika Thirumalasetty
April 10, 2013
Serialized object inserting into database

I created the table in database with name age sex as varchar
DMCA.com