I have multiple SQL prepared statements I want to execute at the same time. Up until now, I had been using a prepared statement method that looks more or less like this:
public PreparedStatement createWordEntry(Connection c, String word, String word2, int num) throws SQLException{
PreparedStatement entry = c.prepareStatement("INSERT INTO table VALUES(?,?,?)");
entry.setString(1, word);
entry.setString(2, word2);
entry.setInt(3,num);
return entry;
}
Originally, I tried adding these to a vector / array and executing them one at a time, but because of intricacies with resultSets and indexing, I kept getting "jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed"
Then I looked into adding all statements into a batch and executing at once. Of course, addBatch() requires a string as opposed to a PreparedStatement as a parameter. When I searched on this site, I found this answer: How to generate String "elegantly" in Java? which suggests building and formatting strings to add to a batch leaves code vulnerable to SQL injection attacks.
So, is there an alternative to these two methods for executing multiple queries at once? If there isn't, which of the above is preferable, and why?