user1128528
user1128528

Reputation: 11

Serializing an ArrayList with JDBC and Oracle

I tried to serialize an ArrayList in order to write it to an ORACLE database.

    ArrayList<Long> lst2 = new ArrayList<Long>();
    lst2.add((long) 5);
    lst2.add((long) 5);
    lst2.add((long) 7);
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     try {
        new ObjectOutputStream( baos ).writeObject( lst2 );
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

SQL Scheme as follows:

 create table T_2471785b1bf2475c9f292f73eeb 
 (
 "CLEARTXTID" NUMBER(38,0),
 "user" VARCHAR2(255),
 "tag" VARCHAR2(255),
 "object" NUMBER(19, 0),
 "objectList" BLOB 
, CONSTRAINT c_f2858bfc2a824579a630a934aea PRIMARY KEY ( "CLEARTXTID"  ) 
)

In order to insert I used the following Java code:

    try
   {
   Class.forName("org.postgresql.Driver");

   Connection conn = DriverManager.getConnection("jdbc:...:testdb", 
       "user", "password");
   Statement statement = conn.createStatement();

    int result = statement.executeUpdate("INSERT INTO T_2471785b1bf2475c9f292f73eeb  VALUES(5, 'Trude', 'Trudscherl',       42, !!serializedArraylist!!);");

   System.out.println("Eingefügte Datensätze: " + result);

   statement.close();
   conn.close();
   }
   catch(ClassNotFoundException e)
   {
   // ...
   }
   catch(SQLException e)
   {
   // ...
   }

I don't know how to put my serialized Arraylist at serializedArraylist.

Upvotes: 1

Views: 540

Answers (2)

mevada.yogesh
mevada.yogesh

Reputation: 1128

String query = "INSERT INTO T_2471785b1bf2475c9f292f73eeb VALUES(5, 'Trude', 'Trudscherl', 42, ";
for (int i = 0; i < lst2.size();) {
    query += lst2.get(i);
    i++;
    if(i<lst2.size()){
        query += ", ";
    }
}
query += ")";
int result = statement.executeUpdate(query);
System.out.println("Eingefügte Datensätze: " + result);

You can update easily using the above code.

Upvotes: 1

Viruzzo
Viruzzo

Reputation: 3025

You should use a PreparedStatement, and set each field parametrically. BLOBs can be a pain to use though, so maybe a VARBINARY or such will be better (provided your data is relatively small, as seems to be the case here).

Upvotes: 1

Related Questions