Here's a quick example of how I just used a Java PreparedStatement to insert nearly 1,500 records into a Drupal database table.
I needed this method (and the corresponding class) because after I converted this website to use Drupal, I did not correctly populate a Drupal database table named workflow_node, so I wrote this method as part of a larger Java program to correct the data in that table:
/**
* A method for inserting records into the workflow_node table.
* This is being done to correct some data after the transition
* to Drupal.
*/
private void insertWorkflowNodeEntries(List<Node> nodes)
throws SQLException
{
// there are nearly 1,500 nodes, but i'm just going to
// give them all the same timestamp
int stamp = 1250629584;
// my SQL INSERT statement
String query = " insert into workflow_node (nid, sid, uid, stamp)"
+ " values (?, 2, 3, ?)";
// declare the preparedstatement reference
PreparedStatement preparedStmt = null;
try
{
// create the preparedstatement before the loop
preparedStmt = mysqlConn.prepareStatement(query);
// now loop through nearly 1,500 nodes in the list
for (Node n : nodes)
{
preparedStmt.setInt(1, n.nid);
preparedStmt.setInt(2, stamp);
preparedStmt.execute(); // the INSERT happens here
}
}
catch (SQLException se)
{
se.printStackTrace();
throw se;
}
finally
{
// close the statement when all the INSERT's are finished
preparedStmt.close();
}
}
I added a lot of documentation to this "PreparedStatement INSERT" method, so hopefully the only thing that needs to be added here is that I defined a small Node class, and when this method is called, it is passed a List of Node references, in this case, almost 1,500 of these Nodes.
As I look at the code, I also need to note that the mysqlConn is our Connection to the MySQL database. This connection needs to be created before this method is called.

