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; } }