Contents Index Lesson 1: Connect to the database Lesson 3: Select the rows from the table

Native UltraLite for Java User's Guide
  Tutorial: An Introductory Application

Lesson 2: Insert data into the database


This lesson shows you how to add data to the database.

To add rows to your database

  1. Add the following method to the Customer.java file:

    private void insert() throws SQLException
    {
      // Open the Customer table
      Table t = conn.getTable( "customer" );
      t.open();
    
      short id = t.schema.getColumnID( "id" );
      short fname = t.schema.getColumnID( "fname" );
      short lname = t.schema.getColumnID( "lname" );
    
      // Insert two rows if the table is empty
      if( t.getRowCount() == 0 ) {
    
          t.insertBegin();
          t.setString( fname, "Gene" );
          t.setString( lname, "Poole" );
          t.insert();
    
          t.insertBegin();
          t.setString( fname, "Penny" );
          t.setString( lname, "Stamp" );
          t.insert();
    
          conn.commit();
          System.out.println( "Two rows inserted." );
      } else {
          System.out.println( "The table has " +
          t.getRowCount() + " rows." );
      }
      t.close();
    }

    This code carries out the following tasks:

  2. Add the following line to the main() method, immediately after the call to the Customer constructor:

    cust.insert();
  3. Compile and run your application, as in Lesson 1: Connect to the database.

The first time you run the application, it prints the following messages:

Connected to an existing database.
Two rows inserted.

Subsequent times, it prints the following messages:

Connected to an existing database.
The table has 2 rows.

Contents Index Lesson 1: Connect to the database Lesson 3: Select the rows from the table