java04_main.java

Indexing. Create 10 rows with random values in indexed column. Select all in order and print.

import java.sql.*;
import java.util.*;
public class java04_main {
/*
* EXAMPLE - java04 for JDBC
* When you run this example, a new database is created with a single table
* that has an index. Ten rows are inserted in random order.
* Finally all the data is read from the database using the index to order
* the results.
*
* 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();
Random rand = new Random();
/* Insert ten rows into the table with random data */
for (int ii = 0; ii < 10; ii++)
{
stmt.executeUpdate("INSERT INTO IndTab VALUES " + (rand.nextInt() % 100));
}
/* Scan through all the existing rows using the index for order */
rs = stmt.executeQuery("SELECT id FROM IndTab order by id");
while (rs.next() != false)
{
System.out.println(rs.getInt(1));
}
}
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 java04");
} catch (SQLException sqle) {}
stmt.execute("CREATE DATABASE java04");
stmt.execute("CREATE TABLE IndTab (id INTEGER PRIMARY KEY)");
conn.commit();
stmt.close();
stmt = null;
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
}