Native UltraLite for Java User's Guide
Tutorial: An Introductory Application
This lesson shows you how to add data to the database.
To add rows to your database
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:
Opens the table. You must open a Table object to carry out any operations on the table. To obtain a Table object, use the connection.getTable() method.
Obtains identifiers for some of the columns of the table. The other columns in the table can accept NULL values or have a default value; in this tutorial only required values are specified.
If the table is empty, adds two rows. To insert each row, the code sets the mode to insert mode using InsertBegin, sets values for each required column, and executes an insert to add the rows to the database.
The commit method is not strictly needed here, as the default mode for applications is to commit operations after each insert. It has been added to the code to emphasize that if you turn off autocommit behavior (for better performance, or for multi-operation transactions) you must commit a change for it to be permanent.
If the table is not empty, reports the number of rows in the table.
Closes the Table object.
Add the following line to the main()
method, immediately after the call to the Customer constructor:
cust.insert();
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.