JDBC - Insert

This chapter demonstrates how to insert records into the NAMECARD table using JDBC. Our goal is to execute the following insert statement.

INSERT INTO NAMECARD VALUES
(
  SEQ_NAMECARD_NO.NEXTVAL,
  'Alison',
  '011-0000-0000',
  '[email protected]',
  'Google Inc'
);

Complete the main() of NamecardInsert.java by referring to the following JDBC programming order.

  1. Loading a JDBC Driver
  2. Getting a Connection
  3. Execute SQL
  4. [If the SQL statement is a select statement, use a ResultSet to process the data.]
  5. Returning Resources
NamecardInsert.java
package net.java_school.jdbc.test;

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

public class NamecardInsert {
  static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
  static final String USER = "scott";
  static final String PASS = "tiger";
	
  public static void main(String[] args) {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
		
    Connection con = null;
    Statement stmt = null;
    String sql = "INSERT INTO NAMECARD VALUES " +
      "(SEQ_NAMECARD_NO.NEXTVAL," +
      "'Alison'," +
      "'011-0000-0000'," +
      "'[email protected]'," +
      "'Google Inc')";

    try {
      con = DriverManager.getConnection(URL, USER, PASS);
      stmt = con.createStatement();
      stmt.executeUpdate(sql);
    } catch (SQLException e) {
      e.printStackTrace();
      System.out.println(sql);
    } finally {
      try {
        stmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      try {
        con.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}

Run NamecardInsert class and confirm via SQL*PLUS that the data exists.