PreparedStatement, addBatch() and setting parameters
Hi,
I am trying PreparedStatement's addBatch(String sql) method. I am trying to execute two(2) Insert statement.
But I am a little confuse how would I set the values for parameters in two insert statement. Trying to google
it but I did not see any example that uses more than one insert statement in one preparedstatement.
Here is what I am trying to do.
Code:
private boolean insertOrder()
{ boolean insertSuccessful = true;
Connection conn = null;
try
{ String url="jdbc:mysql://aComputer:3306/myDatabase";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, "user", "password");
conn.setAutoCommit(false);
}
catch(Exception ex){ ex.printStackTrace(); }
try
{
String sql = "INSERT INTO Table1(Field1, Field2, Field3, Field4) "
+ "VALUES(?, ?, ?, ?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, strForField1);
pst.setString(2, strForField2);
pst.setInt(3, intForField3);
pst.setString(4, strForField4);
sql = "INSERT INTO Table2(FieldA, FieldB, FieldC, FieldD, FieldE, FieldF, FieldG) "
+ "VALUES(?, ?, ?, ?, ?, ?, ?)";
pst.addBatch(sql);
pst.setString(1, strForFieldA);
pst.setString(2, strForFieldB);
pst.setString(3, strForFieldC);
pst.setString(4, strForFieldD);
pst.setString(5, strForFieldE);
pst.setString(6, strForFieldF);
pst.setString(7, strForFieldG);
pst.execute();
pst.clearParameters();
pst.close();
System.out.println("DONE!")
}
catch(Exception ex){ ex.printStackTrace(); }
try{ if(conn != null){conn.close();} }
catch(Exception ex){ ex.printStackTrace(); }
return insertSuccessful;
}
Thanks for the help,
geje