Development Guide

Local Navigation

Using transactions

SQLite® statements always run in transactions. If the statement runs successfully, the transaction is automatically committed. If the statement fails, the transaction is rolled back.

By default, a separate transaction is created for each SQLite statement, which is less efficient than running multiple statements in one transaction. You can usually improve performance by explicitly specifying transactions for groups of statements. You can run multiple statements in one transaction using Database.beginTransaction() and Database.commitTransaction() around groups of statements.

Nested transactions are not supported.

Code sample: Using transactions

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.database.*;
import net.rim.device.api.io.*;
public class UsingTransactions extends UiApplication
{
    public static void main(String[] args)
    {
        UsingTransactions theApp = new UsingTransactions();
        theApp.enterEventDispatcher();
    }
    public UsingTransactions()
    {
		
    }
}

class UsingTransactionsScreen extends MainScreen
{
    Database d;
    public UsingTransactionsScreen()
    {
       LabelField title = new LabelField("SQLite Using Transactions Sample",
       LabelField.ELLIPSIS |
       LabelField.USE_ALL_WIDTH);
       setTitle(title);
       add(new RichTextField(
              "Updating data in one transaction in MyTestDatabase.db."));
       try
       {
          URI myURI = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
              "MyTestDatabase.db");
          d = DatabaseFactory.open(myURI);
			
          d.beginTransaction();
          Statement st = d.createStatement("UPDATE People SET Age=7 " +
              "WHERE Name='Sophie'");
          st.prepare();
          st.execute();
          st.close();
          st = d.createStatement("UPDATE People SET Age=4 " +
              "WHERE Name='Karen'");
          st.prepare();
          st.execute();
          st.close();
          d.commitTransaction();
          d.close();
     }
     catch ( Exception e )
     {
          System.out.println( e.getMessage() );
          e.printStackTrace();
     }
  }
}
Previous topic: Working with blobs

Was this information helpful? Send us your comments.