Java Examples - Retrieve Contents from many Tables
Problem Description:
How to join contents of more than one table & display?
Solution:
Following 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:
The above code sample will produce the following result.The result may vary.
Fname Lname ISBN
john grisham 123
jeffry archer 113
jeffry archer 112
jeffry archer 122