World's most popular travel blog for travel bloggers.

Suppose there is a table named as product in Oracle database with attributes as : product id, product name, product quality, product price, model and its description . Write JAVA program to insert, delete and display records of the table using JDBC.

, , 15 comments

First Create Table in your Database

create database SampleDB;
 
use SampleDB;
 
CREATE TABLE  product (
     product_id  Number NOT NULL AUTO_INCREMENT,
     productname  varchar(45) NOT NULL,
     Quality number NOT NULL,
     Price decimal NOT NULL,
     model varchar(45) NOT NULL,
 description varchar(245) NOT NULL,
    PRIMARY KEY (product_id)
);


Java Code


//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:oracle://localhost/products";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");
      
      //STEP 4: Execute a query
      System.out.println("Inserting records into the table...");
      stmt = conn.createStatement();
      
      String sql = "INSERT INTO Products " +
                   "VALUES (100, 'Mobile 2', 1, 1800, 's7', 'Its a good pfone')";
      stmt.executeUpdate(sql);
       
      System.out.println("Inserted records into the table...");

   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample

15 comments:

  1. href="https://istanbulolala.biz/">https://istanbulolala.biz/
    7İQNH3

    ReplyDelete

Let us know your responses and feedback