1

Is there is a way, in java language, to insert an Arraylist into table without looping through ArrayList and coding:

List<Object> lo = new ArrayList<Object>();
for (Object obj:lo)
{PreparedStatement ps = conn.prepareStatement("INSERT INTO TABLE VALUES (?, ?, ? )");
ps.setString(1,obj.field1); 
ps.setInt(2,obj.field2); } 

But rather just :

   List<Object> lo = new ArrayList<Object>();
   PreparedStatement ps = conn.prepareStatement("INSERT INTO TABLE VALUES (?, ?, ? )");
    ps.insertArray(lo); 
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
code_r
  • 27
  • 1
  • 3
  • Check this: http://stackoverflow.com/questions/4355046/java-insert-multiple-rows-into-mysql-with-preparedstatement – alobodzk Mar 08 '16 at 17:53
  • Im not looking for batch solution, as it just couple Inserts into one call (Database still should hard or soft parse them) , but rather a way to Insert ArrayList or any other Collection by one command/call efficiently. – code_r Mar 08 '16 at 17:55

1 Answers1

0

There isn't. JDBC does not know what value should be used on each insert parameter. You have to explicitly set:

List<MyClass> objects = new ArrayList<MyClass>();

// ...

try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO TABLE VALUES (?, ?, ? )")) {

    objects.stream().forEach(o -> { insert(o, stmt) });

}

private static void insert(MyClass, object, PreparedStatement stmt) {
    stmt.setInt(1, object.getId());
    stmt.setString(2, object.getName());
    ...
    stmt.executeUpdate();
}

Consider using an Object Relational Mapper to achieve what you want.

andrucz
  • 1,971
  • 2
  • 18
  • 30