1. Create a database helper class.
Package Com.wzw.sqllitedemo.db;import Android.content.context;import android.database.sqlite.SQLiteDatabase; Import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.SQLiteOpenHelper; Import android.util.log;/** * * Database helper class for creating the Management database * @author Administrator * */public final class Personsqliteopenhelper ex Tends Sqliteopenhelper {private String tag= "Personsqliteopenhelper";/** * Database constructor * @param context * @param name Database name * @ PARAM factory Cursor Factory * @param version */public Personsqliteopenhelper (context context) {Super (context, "my.db", NULL, 2);} /** * This method is called when the database is first created */@Overridepublic void OnCreate (Sqlitedatabase db) {//sqlitedatabase object is already connected to the database. Direct-to-action database operation string sql= "CREATE table person (_id integer primary key,name varchar (page), age integer);"; Db.execsql (SQL);//create Person table}/** * The database version number is called when updating the contents of the database (delete table, Update table, delete table) */@Overridepublic void Onupgrade ( Sqlitedatabase db, int oldversion, int newversion) {if (oldversion==1&&newversion==2) {///database update, add BALance balance column, transaction processing LOG.I (tag, "database Updated");d b.execsql ("ALTER TABLE person add balance Integer");}}
There are id,name,age,banlance columns in the database table person
2. Create a JUnit test class for testing
Package Com.wzw.sqllitedemo.test;import Java.util.list;import Com.wzw.sqllitedemo.dao.persondao;import Com.wzw.sqllitedemo.db.personsqliteopenhelper;import Com.wzw.sqllitedemo.entities.person;import Android.database.sqlite.sqlitedatabase;import Android.test.androidtestcase;import Android.util.Log;public Class TestCase extends Androidtestcase {private String tag= "TestCase";p ublic Void Test () {//database when to create Personsqliteopenhelper Openhelp=new Personsqliteopenhelper (GetContext ());//The database is created the first time the database is connected, OnCreate calls Openhelp.getwritabledatabase ();} public void Testtransaction () {personsqliteopenhelper openhelper=new personsqliteopenhelper (GetContext ()); Get the database Help class Sqlitedatabase db=openhelper.getwritabledatabase ();//Get Writable database if (Db.isopen ()) {//If the database is readable, operate//1. From Zhang Shan Buckle 1000try{db.begintransaction ();d b.execsql ("Update person set balance=balance-1000 where name= ' Zhangsan ';"); /ATM out abnormal//int tes=1/0;//2. To Li Shiga 1000 yuan Db.execsql ("Update person set balance=balance+1000 where name= ' Lisi ';"); Db.settransactionsuccessful ();//Mark ThingService Success! }finally{db.endtransaction ();d b.close ();}}}
The transaction must be called settransactionsuccessful () to identify the transaction success.
Beginner Android, record a bit of drip.