Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JDBC VRE 2.0 BatchUpdate

 
Monty Ireland
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering if anyone has test multi batch update...
Question:
I i have 5 insert statements with a batch.
The 1st two work ...
The 3rd fails...
The last two work...
How many rows will get inserted afer a commit().

------------------
We learn more from our mistake's than from our success's.
 
menon
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only the first two rows will get commited. Have a look at the following program which demonstrates this.
import java.sql.*;
public class BatchUpdates
{
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
int i = 0;
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection("jdbcracleci8:@deep816", "scott", "tiger");
stmt = conn.createStatement();
try
{
stmt.execute("drop table mytest_table");
}
catch (Exception e1) {}
stmt.execute("create table mytest_table (col1 number(2), col2 varchar2(20))");

pstmt = conn.prepareStatement("insert into mytest_table values (?, ?)");
pstmt.setInt(1, 1);
pstmt.setString(2, "row 1");
pstmt.addBatch();
pstmt.setInt(1, 2);
pstmt.setString(2, "row 2");
pstmt.addBatch();
//This line throws an exception
pstmt.setInt(1, 333);
pstmt.setString(2, "row 3");
pstmt.addBatch();
pstmt.setInt(1, 4);
pstmt.setString(2, "row 4");
pstmt.addBatch();
pstmt.setInt(1, 5);
pstmt.setString(2, "row 5");
pstmt.addBatch();
pstmt.executeBatch();

}
catch (Exception e)
{
e.printStackTrace();
}
finally
{

// Select and print results.
//
rset = stmt.executeQuery("select * from mytest_table");
while (rset.next())
{
System.out.println(rset.getInt(1) + ", " + rset.getString(2));
}
if (stmt != null)
{
try { stmt.close(); } catch (Exception e) {}
}
if (pstmt != null)
{
try { pstmt.close(); } catch (Exception e) {}
}
if (conn != null)
{
try { conn.close(); } catch (Exception e) {}
}
}
}
}
Regards
Ram
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic