Monday, 24 October 2016

Execute the query

Execute the query

  • To execute the query, we need to call execute methods according to our requirement.
  • To create the table, need to call executeUpdate() method.
  • executeUpdate() method presents in java.sql.Statement interface.
Syntax
             public int executeUpdate(String sql)

Example
             String createTable = "create table emp(eno number(5), ename varchar2(10), address varchar2(10)";
             statement.executeUpdate(createTable );
-------------------------------------------------------------------------------------
Program         :       Executing the query to crate a table
Program name  :      ExeQuery1.java
Output             :         
 Driver is Registered successfully
 got Connection from DB success
 Statement object created successfully
 Table created successfully

import java.sql.*;
class ExeQuery1
{
public static void main(String args[])throws SQLException
{
//step-1:Register the JDBC driver

Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
System.out.println(“Registered succesfully”);

//step-2: get the connection from DB server

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","nireekshan");
System.out.println("got Connection from DB"+con);

//step-3 create the Statement object

Statement statement = con.createStatement();
System.out.println("Statement object created successfully");

//step-4 execute the query

String createTableQuery = “create table emp(eno number(5),ename
varchar2(10),address varchar2(10))”;

statement.executeUpdate(createTableQuery);
System.out.println("Table created successfully");
}

}

Note:
To compile above java program we have to set the class path to ojdbc14.jar, so, keep this jar in corresponding directory then set the class path.
Set class path:
  • C:\Nireekshan\JDBC>set classpath=ojdbc14.jar;.;
Compile      :          javac ExeQuery1.java
Run            :          java ExeQuery1
Output        :         
Driver is Registered successfully
got Connection from DB success
Statement object created successfully
Table created successfully
-------------------------------------------------------------------------------------
Thanks for your time.
Nireekshan