Java Example Step 3: Selecting records

Previous Next

After a connection has been established, the various JDBC classes can be deployed to insert, update and retrieve data. This example code fragment retrieves all records from some PERSON table into a JDBC record set. This PERSON table has been defined in a USoft repository.

ResultSet set = null;

try

{

    String sql = "SELECT * FROM Person";

    stmnt = c.createStatement();

    set = stmnt.executeQuery(sql);

}

catch (SQLException e)

{

    System.err.println("Failed t execute query: " + e);

}

 

A generic way to show the contents of this PERSON table is:

//Step 3, continued

if (set != null)

{

    int columns = 0;

    try

    {

        ResultSetMetaData meta = set.getMetaData();

        columns = meta.getColumnCount();

                

        for (int i=1;i<=columns;i++)

        {

            System.out.print(meta.getColumnLabel(i) + "(" + meta.getColumnTypeName(i) + ")");

            System.out.print("\t\t");

        }

        System.out.println();

    }

    catch (SQLException e) {System.err.println(e); }

        

    try

    {

        while (set.next())

        {

            for (int i=1;i<=columns;i++)

            {

                Object obj = set.getObject(i);

                System.out.print(obj);

                System.out.print("\t");

            }

            System.out.println();                            }

    }

    catch (SQLException e){    System.err.println(e); }

}