Executing queries in batch

Executing queries in batch


Posted in : Core Java Posted on : October 18, 2010 at 3:51 PM Comments : [ 0 ]

This section contains the detail about theExecuting queries in batch using jdbc in java.

Executing queries in batch

In Batch processing, many queries work together as batch. The following program include collective set of SQL queries executed altogether to the database.".addBatch()" method is used to add query in "Statement" object and "executeBatch()" method is used to run all queries altogether.

sqlbatch.java


import java.sql.*;

public class Sqlbatch {
	public static void main(String args[]) {

	Connection con = null;
	Statement st = null;
	ResultSet rs = null;
	
	String url = "jdbc:mysql://192.168.10.13:3306/";
	String db = "ankdb";
	String driver = "com.mysql.jdbc.Driver";
	String user = "root";
	String pass = "root";
	
	try {
		Class.forName(driver);
		con = DriverManager.getConnection(url + db, user, pass);
	
		st = con.createStatement();
	
		st
				.addBatch("INSERT INTO cellular "
						+ "VALUES('3036','9560534071')");
		st
				.addBatch("INSERT INTO cellular "
						+ "VALUES('3037','9560534072')");
		st
				.addBatch("INSERT INTO cellular "
						+ "VALUES('3038','9560534073')");
	
		st.executeBatch();
	
		String sql = "select * from cellular ";
		rs = st.executeQuery(sql);
	
		System.out.println("ID  \tMOBILE");
		while (rs.next()) {
			System.out.print(rs.getInt(1) + "   \t");
			System.out.println(rs.getString(2));
		}
		rs.close();
		st.close();
		con.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	}
}

JDBC Video Tutorial: JDBC Batch Query Example

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>java Sqlbatch
ID       MOBILE
3035   998159690
3036   9560534071
3037   9560534072
3038   9560534073
3036   9560534071
3037   9560534072
3038   9560534073
3036   9560534071
3037   9560534072
3038   9560534073
3036   9560534071
3037   9560534072
3038   9560534073

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics