ExecuteUpdate example

ExecuteUpdate: When a java program executes statement ExecuteUpdate, the jdbc driver sends the statement to the server. The server carries out the following steps:
  • The server breaks up the sql statement into multiple tokens and analyzes whether the statement is a valid sql statement or not. During this step the server also checks whether the columns, tables, used in the statement are available or not. This phase is called as "parsing".
  • If parsing is successful then the server executes the statement.
The below code inserts 10 rows by using statement objects executeUpdate method. Every time executeUpdate method is executed the server has to carry out parsing and execute the statement.
In the below program we are using 10 insert statements. They are: insert into sample values(0);
insert into sample values(1);
...
insert into sample values(9);
The above statements are same but with a different set of values. In this case it is better to use preparedStatement instead of statement object. Prepared statement improves the performance by reducing the number of parses. An example on how to use prepared statement can be found here preparedStatement example
Below is a sample program to insert values into "sample" table. Before executing the program, first create a "sample" table in the data base as shown below:
create table sample(id number);
File: com.ram.app.ExecuteExample.java
package com.ram.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class ExecuteExample {
 public static void main(String[] args) throws Exception{
  Class.forName("oracle.jdbc.driver.OracleDriver");
  Connection conn = DriverManager.getConnection("dbc:oracle:thin:@localhost:1521:xe","hr","hr");
  
  Statement stmt = conn.createStatement();
  for(int i=0; i<10; i++){
   String query = "insert into sample values("+i+")";
   stmt.executeUpdate(query);
  }
 }
}

Execute ExecuteExample.java file. Output is given below.

No comments:

Post a Comment