Add

Java Language - Retrieve Contents from many Tables

 

How to join contents of more than one table & display?

Solution

example uses inner join sql command to combine data from two tables. To display the contents of the table getString() method of resultset is used.

import java.sql.*;

public class jdbcConn {

   public static void main(String[] args) throws Exception {

      Class.forName("org.apache.derby.jdbc.ClientDriver");

      Connection con = DriverManager.getConnection (

         "jdbc:derby://localhost:1527/testDb","username", "password");

      Statement stmt = con.createStatement();

      String query ="SELECT fname,lname,isbn from author inner join books on author.AUTHORID = books.AUTHORID";

      ResultSet rs = stmt.executeQuery(query);

      System.out.println("Fname  Lname   ISBN");    

      while (rs.next()) {

         String fname = rs.getString("fname");

         String lname = rs.getString("lname");

         int isbn = rs.getInt("isbn");

         System.out.println(fname + "  " + lname+"   "+isbn);

      }

      System.out.println();

      System.out.println();

   }

}

Result

Fname  Lname   ISBN

john  grisham   123

jeffry  archer   113

jeffry  archer   112

jeffry  archer   122

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.