ExecuteMethod.java Source code

Java tutorial

Introduction

Here is the source code for ExecuteMethod.java

Source

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

public class ExecuteMethod {

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        boolean executeResult;
        try {
            String driver = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driver).newInstance();
            System.out.println("Connecting to database...");
            String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
            conn = DriverManager.getConnection(jdbcUrl, "test", "mypwd");
            stmt = conn.createStatement();

            String sql = "INSERT INTO Employees VALUES" + "(1,'G','4351',{d '1996-12-31'},500)";
            executeResult = stmt.execute(sql);
            processExecute(stmt, executeResult);

            sql = "SELECT * FROM Employees ORDER BY hiredate";
            executeResult = stmt.execute(sql);
            processExecute(stmt, executeResult);
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }

    public static void processExecute(Statement stmt, boolean executeResult) throws SQLException {
        if (!executeResult) {
            int updateCount = stmt.getUpdateCount();
            System.out.println(updateCount + " row was " + "inserted into Employee table.");

        } else {
            ResultSet rs = stmt.getResultSet();
            while (rs.next()) {
                System.out.println(rs.getInt("SSN") + rs.getString("Name") + rs.getDouble("Salary")
                        + rs.getDate("Hiredate") + rs.getInt("Loc_id"));

            }
        }
    }
}