Friday 26 December 2014

JDBC-ODBC Conncection in java with MyEclipse

To run this program you need :
  • Oracle 11g
  • My Eclipse
  • ojdbc1.6.jar
Be sure that if you type in the browser http://localhost:1158/em -then it should be working.
  • If you are facing problem in this then-- Type Services in your  search and program files-(appear when you click in windows button)
  • start all oracle related services.
Then download the ojdbc.1.6.jar file and place that inside your Project directory.
  • Right Click on Project Directory(Inside MyEclipse).
  • go to Build-Configure -Libraries-Add jar -then from the following project add the ojdbc1.6.jar

 Copy and Paste this Code and Run.
import java.sql.*;

public class RetriveEmpInfo {
   
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  
      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      
      conn =DriverManager.getConnection
("jdbc:oracle:thin:@//localhost:1521/orcl","HR","sunilsahu");
  
      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT ename,cname,salary FROM emp_company";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         String ename  = rs.getString("ename");
         String cname = rs.getString("cname");
         int salary = rs.getInt("salary");
        // String last = rs.getString("last");

         //Display values
         System.out.println("Ename: " + ename);
         System.out.println(", Cname: " + cname);
         System.out.println(", Salary: " + salary);
         //System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }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)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end FirstExample
--------------------------------------------------------------------------------------------------------------
most probably you find 2 type of error
1.Number format Exception
2.Driver not found
For this your Step3 of this program should be correct.
If incase you are running XE (oracle)  then replace orcl to XE in step 3.

hope it works for you ,if you face any problem let me know it..

Saturday 13 December 2014

Three letter pattern A string str has been provided as input. The objective is to find three character patterns in str starting with ‘t’ and ending with the char ‘p’. For all such patterns, the middle character is removed. tpPattern(“tiptop”) = “tptp” tpPattern(“tip.tip..tip”) = “tp.tp..tp” tpPattern(“tpttipptptaptptopp”) = “tpttpptptptptpp”

package Module2.module2a.module2c;
import static java.lang.Character.isLowerCase;
/**
 *
 * @author SUNIL
 */


public class LetterPattern {

 static String testcase1 = "Tip.TiP..tip";

 public static void main(String args[]){
 LetterPattern testInstance= new LetterPattern();
 String result = testInstance.changeLetters(testcase1);
 System.out.println(result);
 }

  public String changeLetters(String str){
    String newString="";
    String holdT="";
    String holdP="";
    int i=0;
    //if the case is (tip.....)
    if(str.charAt(0)=='t'&&str.charAt(2)=='p'){
        newString="tp";
        System.out.println("newString is::"+newString);
        i=3;//i will check from (.)
    }
    //else for any case, first two letter extracted and given to newString and i=2,coz (Hellotop)---this case after H and e the i will check from l
    else{
       char tempfirst=' ';
        char tempSecond=' ';
        tempfirst=str.charAt(0);
       
        tempSecond=str.charAt(1);
        newString=str.valueOf(tempfirst)+str.valueOf(tempSecond);
        i=2;
    }
    //if there is t,p present in string then move on else go to line 88.
 if(str.indexOf("t",2)>=1&&str.indexOf("p",2)>=1){    //2nd
    for(i=i;i<str.length();i++){
       
      
       
     if(str.substring(i).length()>2){//this is for tiptoptoooooAB ,in this case AB print and tiptip,in this case after reaching to last tip ,means after t there is no check ,coz if it check then next i and p us going to add in newString.
        
         holdT=str.valueOf(str.charAt(i));
         holdP=str.valueOf(str.charAt(i+2));
       
         if(holdT.equals("t")&&holdP.equals("p")){//actual checking of tip
           
             newString=newString+holdT+holdP;
                    if(i+2>0)//Indexoutof bound exception
                        i=i+2;
                    else
                        break;
            }
            else//if tip case not found
            newString=newString+str.charAt(i);//the extracted char is going to add here.
        
    }

ChangeStringCase Problem Statement Given a string as input, the expected output is a string where the case of all alphabets has been changed.

/*
ChangeStringCase
Problem Statement

Given a string as input, the expected output is a string where the case of all alphabets has been changed.
 */
package Module2.module2a.module2c;

import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;

/**
 *
 * @author SUNIL
 */
public class ChangeStringCase {

 static String testcase1 = "Trisect";

 public static void main(String args[]){
 ChangeStringCase testInstance= new ChangeStringCase();
 String result = testInstance.changeCase(testcase1);
 System.out.println(result);
 }

 public String changeCase(String sentence){
     String newString="";
 for(int i=0;i<(sentence.length());i++){
     //if(sentence.charAt(i)>=65&&sentence.charAt(i)<=90){
     char eachChar=sentence.charAt(i);
     if(isUpperCase(eachChar)){  
     System.out.println("AAAA"+i);
          char changedCase=Character.toLowerCase(sentence.charAt(i));
        
        newString=newString+changedCase;

     }
     else if(isLowerCase(eachChar)){
         System.out.println("aaaaaa"+i);
          char changedCase=Character.toUpperCase(sentence.charAt(i));
         newString=newString+changedCase;
      
     }
     else{
     
         char digit=sentence.charAt(i);
         newString=newString+digit;
        
     }
 }
return newString;
 }
}

Given three strings s1, s2 and s3 as input, return true if there exists at least one character that is present in all 3 strings s1, s2 and s3. presentIn3("trisect", "learn", "code") = true (as e is present is all) presentIn3("Google", "Apple", "Microsoft") = false (as no character is present is all)

public class PresentIn3 {
    static String testcase1="sunil";
    static String testcase2="anil";
    static String testcase3="bidhu";
   
    public static void main(String args[]){
        PresentIn3 testInstance=new PresentIn3();
        boolean result=testInstance.findPresenceOfchar(testcase1,testcase2,testcase3);
        System.out.println(result);
       
    }
    public boolean findPresenceOfchar(String str1, String str2,String str3){
        char temp=' ';
        boolean caseIs=false;
        String foundMax="";
        String foundThisChar="";
        int i=0,countAtStr2=0,countAtStr3=0;
        int lenOfStr2=0,lenOfStr3=0;
        while(str1.length()>0){
            System.out.println("str1 length  issss"+str1.length());
            temp=str1.charAt(i);
            foundThisChar=str1.valueOf(temp);
            System.out.println("foundThisChar issssss"+foundThisChar);
            for(int j=0;j<str2.length();j++){
                System.out.println("jjjjjjjjjjjj"+j);
                if(str2.regionMatches(j, foundThisChar,0,foundThisChar.length())){
                    countAtStr2++;
                    System.out.println("countAtStr2 issssss"+countAtStr2);
                }
            }
            for(int l=0;l<str3.length();l++){
                System.out.println("l issssssss"+l);
                if(str3.regionMatches(l, foundThisChar,0,foundThisChar.length())){
                    countAtStr3++;
                    System.out.println("countAtStr3 isssssss"+countAtStr3);
                }
            }
           
           str1= str1.replace(foundThisChar,"");
            str1=str1.replaceAll("\\s+","");
            System.out.println("str1 isssssss::::"+str1);
            if(countAtStr2==0&&countAtStr3==0)
                caseIs=false;
            else if(countAtStr2>=1&&countAtStr3>=1){
                foundMax=foundMax+temp;
                caseIs=true;
                System.out.println(caseIs);
                break;
            }
            else
                caseIs=false;
        countAtStr2=0;
        countAtStr3=0;
        }
    return caseIs;
    }
   
   
}
 

Given a string as input, return the following output create("1234") = "1234 234 34 4" create("ABCAB") = "ABCAB BCAB CAB AB B" create("ABC") = "ABC BC C" create("") = "" create("X") = "X" create("XY") = "XY Y"

public class ReplaceOneAndPrint {
  static String testcase="ABC ";
    public static void main(String args[]){
        ReplaceOneAndPrint testInstance=new ReplaceOneAndPrint();
        String result=testInstance.checkString(testcase);
        System.out.println(result);
       
    }
    public String checkString(String str){
        String holdReplaceFormat=str;//store the max occurence of char in string
        String newString="";
        String oneWhiteSpace=" ";
        char holdEachChar=' ';//hold each char of the string
      
        int i=0;
        int lenStr=str.length();
        int lenholdReplaceFormat=0;
      
        while(lenStr>0){//check the string len coz each time the string getting shorter
            holdEachChar=holdReplaceFormat.charAt(i);//hold the first char of string each time
          

           holdReplaceFormat=holdReplaceFormat.substring(i+1);
          
            newString = newString+oneWhiteSpace+holdReplaceFormat;
            System.out.println(newString);
           lenholdReplaceFormat=holdReplaceFormat.length();
           lenStr=lenholdReplaceFormat;
            System.out.println("lenStr issss:"+lenStr);
            if(lenStr==1){
                break;
            }
        } 
        newString=str+newString;
    return newString;       
    }       
}
   

Given a string as Input check the maximum number of a character appears in the string

public class CheckMaxChar {
   
    static String testcase1="triseeect coders";
    public static void main(String a[]){
        CheckMaxChar testinstances=new CheckMaxChar();
       char result=testinstances.checkMax(testcase1);
        System.out.println(result);
    }

    public char checkMax(String str) {
        int greater=0;//each time a new char will be greater if this value changes
        int count=0;//only count the number of occurence of each char
        char max=' ';//return the max of all char
        char temp=' ';//store the first letter of a string
        int i=0;
       
        while(str.length()>0){//each time the len of string is decreasing by replacing checking char with whitespace
            temp=str.charAt(i);//extract the first char
            String stringValueOf = String.valueOf(temp);//convert that to string
            System.out.println(i+"stringValueOf  iss   :"+stringValueOf);
            for(int j=0;j<str.length();j++){//check the input char number of appearnce
                if(str.regionMatches(j, stringValueOf, 0, stringValueOf.length())){
                    count++;//increase each time it found one of the char
                   
                   
                    System.out.println(j+"temp isss:"+temp);
                    System.out.println("greater is   :"+greater);
                    System.out.println("count is     :"+count);
                }
               
            }
       
            str=str.replace(stringValueOf," ");//replace the checked char with whitespace
            str=str.replaceAll("\\s+","");//wipe out all whhite space
            System.out.println("now the string is "+str);
       
       
           if(count>greater){//check the current char appearence with preveous greater char appearence
               greater=count;
               System.out.println("now the greater is   :"+greater);
               max=temp;//change the max char
               System.out.println("max is  :"+max);
               System.out.println("-----------------------------");
               count=0;
               i=0;
           }
          
           
        } 
   
   
    return max;
    }
   
}

Given a string as input, return a string containing the characters that appear at least twice in the string char2Times("hello") = "l" (l is present at least twice) char2Times("trisect teaches code ") = "tsec" (t,e,c are present at least twice) char2Times("India") = "" (no char is present at least twice)

public class Char2Times {
    static String testcase="ssuunnnilkm  3434 66 ## zxqho";
    public static void main(String args[]){
        Char2Times testInstance=new Char2Times();
        String result=testInstance.checkString(testcase);
        System.out.println(result);
       
    }
    public String checkString(String str){
        String holdMaxChar="";//store the max occurence of char in string
        char holdEachChar=' ';//hold each char of the string
        int count=0,i=0;
        while(str.length()>0){//check the string len coz each time the string getting shorter
            holdEachChar=str.charAt(i);//hold the first char of string each time
            String stringValueOf=str.valueOf(holdEachChar);//convert the char to string
            for(int j=0;j<str.length();j++){//loop will check the number of occurence of each  char
                if(str.regionMatches(j,stringValueOf,0, stringValueOf.length())){//this will check the number of occurence of char from j=0, each time and when j increases from that point
                    count++;//increase the count if find the char
                }
            }
            str=str.replace(stringValueOf,"");//replace with white space the char checked
            str=str.replaceAll("\\s+","");//wipe out all white space
            if(count>=2){//if more than two times found the char inside the string then move on
                holdMaxChar=holdMaxChar+stringValueOf;//store the max char
               
            }
            count=0;//coz each time the loop will check the occurence starts from 0 count value
        } 
    return holdMaxChar;       
    }       
}