I'm trying to work with PreparedStatement and the addBatch.
I tried to use the first query (query1) also as a PreparedStatement but
it doesn't work.
For some reason it only adds the last query (query3).
Any suggestions why it works like this?
Are there some errors in my code?
public void testPrepareStatement() throws SQLException {
PreparedStatement ps = null;
Statement st = null;
String query1 = "CREATE TABLE test3 (i int, s varchar(255))";
String query2 = "INSERT INTO test3 VALUES (?,?)";
String query3 = "INSERT INTO test3 VALUES (?,?)";
st = connection.createStatement();
st.executeUpdate(query1);
st.close();
ps = connection.prepareStatement(query2);
ps.setInt(1, 1);
ps.setString(2, "TESTI1");
ps.addBatch();
ps = connection.prepareStatement(query3);
ps.setInt(1, 2);
ps.setString(2, "TESTI2");
ps.addBatch();
int ret[] = ps.executeBatch();
System.out.println(ret.length);
}
Shmuel.
> I'm trying to work with PreparedStatement and the addBatch.
> I tried to use the first query (query1) also as a PreparedStatement but
[quoted text clipped - 3 lines]
> Any suggestions why it works like this?
> Are there some errors in my code?
Hi, yes. You should re-assign ps a second time with a second call
to prepareStatement. This over-writes the first statement, which
makes it uinaccessible and never executed. Use *the one* ps value you
have. After the first call to addBatch(), set the parameter values
again and call addBatch() again, then execute it.
Joe Weinstein at BEA
> public void testPrepareStatement() throws SQLException {
>
[quoted text clipped - 26 lines]
>
> Shmuel.
Shmuel - 04 Jul 2004 12:05 GMT
You know, I think I am just doing that!
Could you show the right way ?
I just don't get it.
// Change the statement
ps = connection.prepareStatement(query2);
ps.setInt(1, 1);
ps.setString(2, "TESTI1");
// Add it to the batch
ps.addBatch();
// Change the statement
ps = connection.prepareStatement(query3);
ps.setInt(1, 2);
ps.setString(2, "TESTI2");
// Add it to the batch
ps.addBatch();
// And then execute the batch
int ret[] = ps.executeBatch();
> Joe Weinstein wrote:
> Hi, yes. You should re-assign ps a second time with a second call
[quoted text clipped - 4 lines]
>
> Joe Weinstein at BEA
Shmuel - 04 Jul 2004 21:10 GMT
Ok, now I think I understood what you meant.
The adBatch is for running the same Statement again and again.
I cannot change the Statement or else I overwrite it.
Only the parameters can be changed.
Am I right?
Joe Weinstein - 04 Jul 2004 22:58 GMT
> Ok, now I think I understood what you meant.
> The adBatch is for running the same Statement again and again.
>
> I cannot change the Statement or else I overwrite it.
> Only the parameters can be changed.
> Am I right?
right. Associate a prepared statement with the SQL it is originally
constructed, and change only the parameter values until you're
done with that SQL. Then close the statement.
Joe