Search code examples
javasqljdbcoracle-xe

How to display record from oracle database using select keyword


I want to display a record from an Oracle database in Java using select keyword, but it's not working. When I run the program it displays the SQL command but not the result I want.

My code is like this:

static void modify()
{
  System.out.println("Enter employee ID");
  empid=sc.nextInt();
  try{
       con=Connection1.getConnection();
       stmt=con.createStatement();
       String d="select * from emp where empid='"+empid+"'";
       rs=stmt.executeQuery(d);
       System.out.println(""+d); 
   }
    catch(SQLException e)
  {
    e.printStackTrace();
  }       
}

When I run the application this result is shown instead of record from database:

select * from emp where empid='14'

Solution

  • The problem is you are just printing the name of your results not the results itself.

    I have changed your code as below,

      static void modify()
        {
        System.out.println("Enter employee ID");
            empid=sc.nextInt();
           try{
                con=Connection1.getConnection();
                stmt=con.createStatement();
                String d="select * from emp where empid='"+empid+"'";
                rs=stmt.executeQuery(d);
    
        while(rs.next()){
    
         //Getting column value from record by giving column no 
                    System.out.println(rs.getString(1)); //line 1
        //Getting column value from record by giving column name,
                    System.out.println(rs.getString("empid"));// line 2
        }
           }
           catch(SQLException e)
           {
               e.printStackTrace();
           }
    
        }
    

    Please note that above code (line 1) will print the first column of your each records( returned from db), here the order of the returned columns is not guaranteed.

    If you want to get Specific column then you can specify the column name as argument in the getString method of resultSet (line 2).

    You have to use appropriate methods to get values such that , if column 2 has the data type in DB as INTEGER then you have to use rs.getInt(2).

    In your code,

     System.out.println(""+rs);
    

    In Java when you call println(Object) method in System.out,which will call String.valueOf(Object) method which is again will call toString() method, which would return the String representation of your object, here nothing but the query you passed, not the records.