java03_main.java
Hierarchy. Same as 02_java but with three tables.
import java.sql.*;
public class java03_main {
/*
* EXAMPLE - 03_java for JDBC
* When you run this example, a new database is created with three tables
* in a hierarchy where one references another, which references the third
* one. Then a single row is created in the top table and three rows are
* created in the middle table and nine rows in the bottom table.
* Finally all the data is read from the database using a join.
*
* Full documentation for RDM is available at http://docs.raima.com/rdm/
*
* For simplicity this example utilizes basic exception handling
* but good programming practices would dictate that this occur in
* a full application.
*/
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
/* Create the connection with a simple connection string */
conn = DriverManager.getConnection("jdbc:raima:rdm://local");
conn.setAutoCommit(true);
CreateDatabase(conn);
/* Open the connection to the database */
stmt = conn.createStatement();
/* Insert a row into the top table */
stmt.executeUpdate("INSERT INTO TopTab VALUES 1, 'top 1'");
/* Insert three rows into the middle table */
for (int ii = 1; ii < 5; ii++)
{
stmt.executeUpdate("INSERT INTO MidTab VALUES " + ii + ", 'mid " + ii +"', 1");
for (int jj = 1; jj < 4; jj++)
{
stmt.executeUpdate("INSERT INTO BotTab VALUES 'bot " + ((ii - 1) * 3 + jj) + "', " + ii);
}
}
/* Scan through all the existing rows using a join and display the contents */
rs = stmt.executeQuery("SELECT tstr, mstr, bstr FROM TopTab, MidTab, BotTab WHERE TopTab.tid = MidTab.tid AND MidTab.mid = BotTab.mid");
while (rs.next() != false)
{
System.out.println(rs.getString(1) + " -- " + rs.getString(2) + " -- " + rs.getString(3));
}
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(conn != null)
conn.close();
}
}
private static void CreateDatabase(Connection conn)
{
Statement stmt = null;
try
{
/* Create the example database */
stmt = conn.createStatement();
/* Since the database is created here, it cannot be created twice */
try {
stmt.executeUpdate("DROP DATABASE java03");
} catch (SQLException sqle) {}
stmt.execute("CREATE DATABASE java03");
stmt.execute("CREATE TABLE TopTab (tid INTEGER PRIMARY KEY, tstr CHAR(30))");
stmt.execute("CREATE TABLE MidTab (mid INTEGER PRIMARY KEY, mstr CHAR(30), tid INTEGER REFERENCES TopTab(tid))");
stmt.execute("CREATE TABLE BotTab (bstr CHAR(30), mid INTEGER REFERENCES MidTab(mid))");
conn.commit();
stmt.close();
stmt = null;
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
}