views:

75

answers:

1

Is this the correct syntax for a prepared statement in java:

INSERT INTO table (id, version, data)
  VALUES (?, ?, ?)
  ON DUPLICATE KEY UPDATE 
    data = IF(version > values(version), data, values(data)),
    version = IF(version > values(version), version, values(version))

I am looking for the best way to insert or update millions of rows from within a for-loop in java taking advantage of PreparedStatement's addBatch.

+1  A: 

If the SQL statement is correct, you need to wrap it as follows:

String sql = ...
PreparedStatement prep;
prep = conn.prepareStatement(sql);
prep.setInt(1, x);
prep.setString(2, y);
prep.setString(3, z);
prep.execute();

To use addBatch, use:

String sql = ...
PreparedStatement prep;
prep = conn.prepareStatement(sql);
for (...) {
    prep.setInt(1, x);
    prep.setString(2, y);
    prep.setString(3, z);
    prep.addBatch();
}
prep.execute();
Thomas Mueller
Thomas, I got this part but my question is, whether the sql syntax is correct.. you know how prepared statements parse question marks.. i just wanted to know if `values(data)` is the right way to say `use whatever value was passed to the data column`
Mohamed Nuur
I'll go ahead and give you credit for the answer even though it doesn't answer my exact question. I guess the fault is on me for not being very clear in my original question.
Mohamed Nuur