Add

Jdbc Program to Insert records into the database.

3:29:00 PM Rohit Kumar Verma 0 Comments

Prerequisite:
Oracle: Any version , Tested on Oracle 12c.
Java 64 bit: Tested on version 7.0, from 8.0 JDBC Driver removed.



//InsertQuery.java
/* Program to take the data from end user
 * and insert it into the database table
 */
package com.rkv.jdbc;
//Import the packages
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class InsertQuery {
 public static void main(String[] args) {
  //Declaring public variable
 Connection con = null;
 Statement st = null;
 Scanner sc = null;
 try{
  //Requesting Input from end-user
  sc = new Scanner(System.in);
  System.out.println("Enter Student number : ");
  String no = sc.next();
  System.out.println("Enter Student name : ");
  String name= sc.next();
  //arranging data according to the requirement
  name="'"+name+"'";
  //registering connection
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  con = DriverManager.getConnection("jdbc:odbc:oradsn","c##scott","tiger");
  //Creating Statement
  if(con!=null){
  st= con.createStatement();
  int s=st.executeUpdate("insert into student values("+no+" "+name+")");
  //Checking response
  if(s==0)
   System.out.println("Records Inserted Sucessfully ");
  else
   System.out.println("Error Inserting Records");
  }
 }
 catch(ClassNotFoundException ce){
 System.out.println("Class Not Found or Missing");
 }
 catch(SQLException ce)
 {
  System.out.println("Sql Exception occured contact Administrator");
 }
 catch(Exception ce)
 {
  System.out.println(ce);
 }

 finally
 {
  //Closing the connection objects
  try{
   if(st!=null){
    st.close();
    System.out.println("Statement Connection Closed sucessfully");
   }
  }
  catch(SQLException ce){
   System.out.println("Connection not closed ");
  
  }
  try{
   if(con!=null){
    con.close();
    System.out.println("Connection to the server Closed sucessfully");
   }
  }
  catch(SQLException ce){
   System.out.println("Error closing connection to the server ");
  }
 }
 }
 }

0 comments: