Tech Rocks

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more...

Sunday, October 31, 2010

Batch Inserts to Oracle using Java

See the following example:

import java.sql.*;

public class ExamplePreparedStatementBatch {
public static void main(String[] args) {
Connection con = null;
try {
oracle.jdbc.pool.OracleDataSource ds = new oracle.jdbc.pool.OracleDataSource();
ds.setDriverType("thin");
ds.setServerName("localhost");
ds.setPortNumber(1521);
ds.setDatabaseName("XE");
ds.setUser("hr");
ds.setPassword("abcd");
con = ds.getConnection();

PreparedStatement ps = con
.prepareStatement("INSERT INTO contact (cnid, cnname)"
+ " VALUES (?, ?)");

ps.setInt(1, 10);
ps.setString(2, "X");

ps.addBatch();

ps.setInt(1, 11);
ps.setString(2, "X");

ps.addBatch();

ps.setInt(1, 12);
ps.setString(2, "X");

ps.addBatch();

ps.setInt(1, 13);
ps.setString(2, "X");

ps.addBatch();

int[] counts = ps.executeBatch();

int count = 0;
for (int i = 0; i <>
count += counts[i];
}
System.out.println("Total effected rows: " + count);

ps.close();

con.close();
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
e.printStackTrace();
}
}
}

0 comments :