使用事务操作SQLite数据库

在使用SQLite数据库时,有时会遇到异步操作,这时就需要使用SQLite数据库事务来处理问题了。

使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTransaction()之前调用了setTransactionSuccessful() 方法设置事务的标志为成功则提交事务,如果没有调用setTransactionSuccessful() 方法则回滚事务。

public void payment() {
		// 如果要对数据进行更改,就调用此方法得到用于操作数据库的实例,该方法以读和写方式打开数据库
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		// 开启事务
		db.beginTransaction();
		try {
			db.execSQL("update person set amount=amount-10 where personid=?",
					new Object[] { 1 });
			db.execSQL("update person set amount=amount+10 where personid=?",
					new Object[] { 2 });
			// 设置事务标志为成功,当结束事务时就会提交事务
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}


/***********/

MainActivity.java的实现方法有两种操作SQLite数据库

(1)

package cn.itcast.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.itcast.domain.Person;
import cn.itcast.service.PersonService;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
    private PersonService personService;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        this.personService = new PersonService(this);
       
        ListView listView = (ListView) this.findViewById(R.id.listView);
    
        List persons = personService.getScrollData(0, 5);
        List> data = new ArrayList>();
        for(Person person : persons){
        	HashMap item = new HashMap();
        	item.put("id", person.getId());
        	item.put("name", person.getName());
        	item.put("amount", person.getAmount());
        	data.add(item);
        }
        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
        		new String[]{"id", "name", "amount"}, new int[]{R.id.id, R.id.name, R.id.amount});
        listView.setAdapter(adapter);
        
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				ListView lView = (ListView)parent;
				HashMap item = (HashMap)lView.getItemAtPosition(position);
				Toast.makeText(MainActivity.this, item.get("id").toString(), 1).show();
			}
		});



 (2) 
  

package cn.itcast.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import cn.itcast.domain.Person;
import cn.itcast.service.CopyOfPersonService;

public class MainActivity extends Activity {

	private CopyOfPersonService copyOfPersonService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		this.copyOfPersonService = new CopyOfPersonService(this);
		ListView listView = (ListView) this.findViewById(R.id.listView);

		Cursor cursor = copyOfPersonService.CopyOfgetCursorScrollData(0, 5);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(
				MainActivity.this, R.layout.item, cursor, new String[] { "_id",
						"name", "amount" }, new int[] { R.id.id, R.id.name,
						R.id.amount });
		listView.setAdapter(adapter);
	        listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView parent, View view, int position, long id) {
					ListView listView = (ListView)parent;
					Cursor data = (Cursor)listView.getItemAtPosition(position);
					int personid = data.getInt(data.getColumnIndex("_id"));
					Toast.makeText(MainActivity.this, personid+"", 1).show();
				}
			});
/*****/注意:

在使用SimpleCursorAdapter显示SQLite数据库时,必须注意SQLite数据表的主键名,由于SimpleCursorAdapter的方法只识别"_id"。所以,当用到SQLite的SimpleCursorAdapter时,就必须把数据表的主键命名为"_id"。否则,就会出现“ java.lang.IllegalArgumentException:column'_id' does not exist ”的异常。

显示的结果:

使用事务操作SQLite数据库_第1张图片

在调用payment()方法之后,就会实现事务的操作。之后显示的结果:会对第一条记录的amount-10,第二条记录的amount+10操作。

在调用payment()方法,我使用的是Android JUnit Test来测试的。

使用事务操作SQLite数据库_第2张图片


代码:      http://download.csdn.net/detail/u012301841/7609897


你可能感兴趣的:(Android,开发记录)