您的位置:首页 > 移动开发 > Android开发

android 实现SQLite开启事务

2016-05-05 13:52 555 查看
1.自定义DatabaseHelper类继承SQLiteOpenHelper


public class DatabaseHelper extends SQLiteOpenHelper{

//类没有实例化,是不能用作父类构造器的参数,必须声明为静态

private final static String DBNAME=A.DB_NAME;//数据库名称

private final static int version = 1; //数据库版本

public DatabaseHelper(Context context) {
//第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
super(context, DBNAME, null, version);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(A.DBTABLE_COUNT);
db.execSQL(A.DBTABLE_TIMES);
}
/**数据库更新**/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

}


2.数据库操作类

/** SQL操作类 **/
public class DBexecSQL {

DatabaseHelper db;

private Context context;

public DBexecSQL(Context context) {
this.context = context;
//实例化SQLiteDatabase
db = new DatabaseHelper(context);
}
/**
* @see查看表中是否有数据
*/
public boolean isEmptyTable(String tableName) {

SQLiteDatabase base = db.getReadableDatabase();
Cursor cursor = base.query(tableName, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
return true;
}
return false;
}
/**
* 添加数据表
*/
public long addChild(List<TableEntity> entity) {
SQLiteDatabase base = db.getReadableDatabase();
// 开启事务
base.beginTransaction();

long l = 0;
try {
ContentValues values;
TableEntity child;
for (int i = 0; i < entity.size(); i++) {
child = entity.get(i);
values = new ContentValues();
values.put("id", child.getCid());
values.put("price", child.getPrice());
values.put("time", child.getTime());
values.put("volumn", child.getVolumn());
l = base.insert(A.TABLENAME_c, null, values);
l += l;
}
// 设置事务标志为成功,当结束事务时就会提交事务
base.setTransactionSuccessful();
} catch (Exception e) {
// TODO Auto-generated catch block
}

finally {

// 结束事务

base.endTransaction();
}

return l;
}

/**
* 获取表中的数据
*/
public List<TableEntity> allofMain(String table) {
SQLiteDatabase base = db.getWritableDatabase();
List<TableEntity> list = new ArrayList<TableEntity>();
TableEntity entity;
Cursor cursor = null;
try {
cursor = base.query(table, null, null, null, null, null, null);
if (table == A.TABLENAME_P) {
while (cursor.moveToNext()) {
entity = new TableEntity();
entity.setFid(cursor.getString(cursor.getColumnIndex("fid")));
entity.setCode(cursor.getString(cursor.getColumnIndex("code")));
entity.setTag(cursor.getInt(cursor.getColumnIndex("tag")));
list.add(entity);
}
} else {
while (cursor.moveToNext()) {
entity = new TableEntity();
entity.setCid(cursor.getString(cursor.getColumnIndex("cid")));
entity.setPrice(cursor.getString(cursor.getColumnIndex("price")));
entity.setTime(cursor.getString(cursor.getColumnIndex("time")));
list.add(entity);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

finally {
if (null != cursor) {
cursor.close();
}
}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: