0

My goal is sql-escaping in bulk-insert query. Eg:

INSERT INTO log VALUES (0,5,-7,'str'), (4,0,0,'str'), (0,0,0,'str'); 

The code inserts in table about 100-200 records each 30 seconds. (Log pooling).
I didn't find way to use PreparedStatement for bulk-insert, so i had to manually build that query through StringBuilder.
But i have no idea how to escape strings, don't really much want apply something like kludge-fixes (Quotes escaping through regex-replace etc).

Is there any handy way?

4
  • 1
    You leave yourself at a high risk if you dont use the PreparedSQL.... Commented Apr 2, 2012 at 20:00
  • 2
    I think this answer about bulk inserts with PreparedStatement is what you are looking for: stackoverflow.com/a/6892457/1272477 Commented Apr 2, 2012 at 20:02
  • mguymon, Probably that's solution. I missed this out. Btw, is this addBatch/executeBatch is Bulk-insert like example above, or set of INSERT queries which will be executed in one pass? Commented Apr 2, 2012 at 20:25
  • possible duplicate of Bulk insert in Java using prepared statements batch update Commented Apr 2, 2012 at 22:46

2 Answers 2

1

Two ways so far i know.

1st Way

Its insert record one by one final String sql = "INSERT INTO tablename(columnname) Values(?)"; PreparedStatement statement = connection.prepareStatement(sql); while (condition) { statement.setString(1,value); statement.executeUpdate(); } 

2nd way

It inserts all record as bulk insert

final String sql = "INSERT INTO tablename(columnname) Values(?)"; PreparedStatement statement = connection.prepareStatement(sql); while (condition) { statement.setString(1,value); statement.addBatch(); } statement.executeBatch(); 
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use PreparedStatement and possibly batch insert. See http://www.exampledepot.com/egs/java.sql/BatchUpdate.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.