日期:2014-05-16  浏览次数:20500 次

android SQLite数据库的增删改查以及事务的单元测试
废话少说,为了这个数据库整理一两天的时间,下面就把代码直接贴出来:

创建androidproject   名称:db

创建包名:com.gohighsoft.db

新建一个Person实体类:

package com.gohighsoft.db;

public class Person {
private Integer id;
private String name;
private Integer age;

public Person() {
};

public Person(String name, Integer age) {
  this.name = name;
  this.age = age;
}

public Integer getId(){
         return id;
     }

public void setId(Integer id) {
  this.id = id;
}

public String getName() {
  return name;
}

public void setName(String name) {
  this.name = name;
}

public Integer getAge() {
  return age;
}

public void setAge(Integer age) {
  this.age = age;
}

public String toString() {
  return "Person [age=" + age + ",id=" + id + ",name" + name + "]";
}
}

新建工具类:

DataBaseHaler.java

package com.gohighsoft.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;

public class DataBaseHaler extends SQLiteOpenHelper {
private static final String NAME = "sharp.db";// 。db可有可无
private static final int version = 1;// 版本号不能为0

public DataBaseHaler(Context context) {
  super(context, NAME, null, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
  Log.i("aa","1111111111111");
  db.execSQL("CREATE TABLE person(personid integer primary key autoincrement,name varchar(20),age integer)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVewsion) {
  Log.i("aa","22222222222222");
  db.execSQL("DROP TABLE IF EXISTS PERSON");
  onCreate(db);
}
}


新建一个service服务类:

PersonService.java

package com.gohighsoft.db;

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

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class PersonService {
private DataBaseHaler databaseHelper;
private Context context;

public PersonService(Context context) {
  this.context = context;
  databaseHelper = new DataBaseHaler(context);
}

public void savesTrannces(Person person) {
  Log.i("aa", "4444444444444");
  SQLiteDatabase db = databaseHelper.getWritableDatabase();
  db.beginTransaction();// 开始事务
  try {
  
   for(int i=0;i<100;i++){
    db.execSQL("insert into person(name,age) values(?,?)",
      new Object[] { person.getName(), person.getAge() });
   }
   db.execSQL("insert into personww(namedd,age) values(?,?)",
     new Object[] { person.getName(), person.getAge() });
   db.setTransactionSuccessful();
  } catch (Exception e) {
   //db.endTransaction();// 事务结束;
   Log.i("aa","wwwwwwwwwwwwwwwwwwwwwwwww");
  }
  db.endTransaction();// 事务结束;
  Log.i("aa", "55555555555555555555");
}

public void save1(Person person) {
  SQLiteDatabase db = databaseHelper.getWritableDatabase();
 
  db.beginTransaction();// 开始事务
  Log.i("aa", "uuuuuuuuuuu