Tuesday, August 25, 2015

JDBC- Execute INSERT query using Statement's executeUpdate method in java

java.sql.Statement's executeUpdate method can be used for executing INSERT queries and
executeUpdate method returns number of rows inserted


--Before executing java program execute these database scripts  >
create table EMPLOYEE(ID number(4), NAME varchar2(22));
commit;
--If table already exists then execute the DROP command >
drop table EMPLOYEE;


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

public class StatementInsertTest {
   public static void main(String... arg) {
          Connection con = null;
          Statement stmt = null;
          try {
                 // registering Oracle driver class
                 Class.forName("oracle.jdbc.driver.OracleDriver");
                 // getting connection
                 con = DriverManager.getConnection(
                              "jdbc:oracle:thin:@localhost:1521:orcl",
                              "ankit", "Oracle123");
                 System.out.println("Connection established successfully!");
                
                 stmt = con.createStatement();
                 //execute insert query
                 int numberOfRowsInserted=stmt.executeUpdate("INSERT into EMPLOYEE(ID,NAME)"
                                                                                                                                        + "values (1, 'ankit') ");

                 System.out.println("numberOfRowsInserted=" + numberOfRowsInserted);
          } catch (ClassNotFoundException e) {
                 e.printStackTrace();
          } catch (SQLException e) {
                 e.printStackTrace();
          }
          finally{
                 try {
                       if(stmt!=null) stmt.close(); //close Statement
                       if(con!=null) con.close(); // close connection
                 } catch (SQLException e) {
                       e.printStackTrace();
                 }
          }
   }
}
/*OUTPUT
Connection established successfully!
numberOfRowsInserted=1
*/

No comments:

Post a Comment