Followers

JDBC: Insertion using PreparedStatement

package com.pack1;

import java.io.DataInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertPrePared {  
   
    public static void main(String[] args) throws Exception
    {
        Connection con = null;
     
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            String url = "jdbc:derby://localhost:1527/hari";
            con = DriverManager.getConnection(url, "app","app");
            String query = "insert into MYEMP values(?,?,?,?)";
            PreparedStatement pstmt = con.prepareStatement(query);
           DataInputStream din = new DataInputStream(System.in);
           while(true){
           System.out.println("Please enter the number to be inserted.");
           int no = Integer.parseInt(din.readLine());
           System.out.println("Please enter the name.");
           String name = din.readLine();
           System.out.println("Please enter the salary.");
           float salary = Float.parseFloat(din.readLine());
           System.out.println("Please enter the address.");
           String address = din.readLine();
           pstmt.setInt(1, no);
           pstmt.setString(2, name);
           pstmt.setFloat(3, salary);
           pstmt.setString(4, address);
           int count = pstmt.executeUpdate();
           if(count > 0)
           System.out.println("Record inserted sucessfully..");
           else
           System.out.println("Record insertion failed..");
           System.out.println("Insertion of another record is required (yes/no)");
           String choice = din.readLine();
           if(!choice.equalsIgnoreCase("yes"))
               break;          
           }
    }
}

No comments:

Post a Comment