Android中sqlite基本使用2,(使用事务实现数据完成或回滚)

还是在上一篇中的例子基础上写的,绿色部分就是实现事务的代码:

核心代码如下:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button 
        android:id="@+id/btn_replace_data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="替换"        
        />

  
    <Button
        android:id="@+id/create_btn_database"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="创建数据库" />


    <Button
        android:id="@+id/btn_adddata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="添加数据" />
     <Button
        android:id="@+id/btn_updatedata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="更新数据" />
     <Button
        android:id="@+id/btn_deletedata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="删除数据" />
     <Button
        android:id="@+id/btn_query_data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="查询数据" />
   
</LinearLayout>

MainActivity

/**
 * 本项目是对事务的使用
 * 事务的特性就是可以保证让某一系列的操作要么全部完成,要么都不完成。(就是要么提交,要么回滚)
 *
 */
public class MainActivity extends Activity {


private MyDatabaseHelper dbHelper;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* 创建数据库
*/
// 指定数据库的名称BookStore.db,版本号是1
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
Button createDatabase_btn = (Button) findViewById(R.id.create_btn_database);
createDatabase_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
// 得到一个能写的数据库
dbHelper.getWritableDatabase();


}
});
/**
* 添加数据
*/
Button addData_btn = (Button) findViewById(R.id.btn_adddata);
addData_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
/* SQLiteDatabase类才能对数据库操作,即增删改查 */
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("name", "The Da Vinci code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values);// 插入第一条数据
values.clear();
// 开始组装第二条数据
values.put("name", "The Lost Symbol");
values.put("author", "Dan Brown");
values.put("pages", 510);
values.put("price", 19.95);
db.insert("Book", null, values);// 插入第二条数据
Toast.makeText(MainActivity.this, "数据已添加", 10).show();

// /**除了可以用android分装的方法进行增删该查,还可以直接用sql语句
// * 下面是用方法实现相同功能,增删改都调用execSQL两个参数的方法,查询调用rawQuery方法*/
// //增加
// db.execSQL("insert into Book(name,author,pages,price)values(?,?,?,?)",new String[]{"The Da Vinci Code","Dan Brown","454","16.96"});
// db.execSQL("insert into Book(name,author,pages,price)values(?,?,?,?)",new String[]{"The Lost Symbol","Dan brown","510","19.95"});
// //删除
// db.execSQL("delete from Book where pages >?", new String[]{"500"});
// //更新
// db.execSQL("update Book set price=?where name=?", new String[]{"10.99","The Da Vinci Code"});
// //查询
// db.rawQuery("select*from Book", null);

}
});
/**
* 更新数据
*/
Button updatedata_btn = (Button) findViewById(R.id.btn_updatedata);
updatedata_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name=?",
new String[] { "The Da Vinci code" });
/* 上述代码的意思是:将名字是The Da Vinci Code 这本书的价格改成10.99 */
Toast.makeText(MainActivity.this, "修改成功", 10).show();
}
});
/**
* 删除数据
*/
Button deletedata_btn = (Button) findViewById(R.id.btn_deletedata);
deletedata_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Book", "pages>?", new String[] { "500" });
/* 删除页数超过500的书籍 */
Toast.makeText(MainActivity.this, "删除成功", 10).show();
}
});
/**
* 查询数据
*/
Button querydata_btn = (Button) findViewById(R.id.btn_query_data);
querydata_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Book", null, null, null, null, null,
null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor
.getColumnIndex("name"));
String author = cursor.getString(cursor
.getColumnIndex("author"));
int pages = cursor.getInt(cursor
.getColumnIndex("pages"));
double price = cursor.getDouble(cursor
.getColumnIndex("price"));
Log.d("1", "name。。。" + name);
Log.d("1", "author。。。" + author);
Log.d("1", "pages。。。" + pages);
Log.d("1", "price。。。" + price);


} while (cursor.moveToNext());
cursor.close();


}
Toast.makeText(MainActivity.this, "查询成功", 10).show();


}
});
/**
* 替换,事务的使用
*/
Button replaceData = (Button) findViewById(R.id.btn_replace_data);
replaceData.setOnClickListener(new OnClickListener() {
/*事务的标准用法
* 1开启事务db.beginTransaction();
* 2事务已经执行成功db.setTransactionSuccessful()
* 3结束事务db.endTransaction();
* 下面的代码,注意观察,在删除旧数据的操作完成后手动抛出一个NullPointerException()
* 这样添加新数据的代码就执行不到了(如果没有事务就属于,删除数据,但是没有添加)。
* 不过由于事务的存在,中途出现的异常会导致事务失败,此时旧数据是删不掉的
* 如果手动将抛出异常的代码去掉,在重新运行一下程序,点击按钮就发现数据更新了
* */

@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();//开启事务
                try {
                db.delete("Book", null, null);
                if (true) {
//这里手动抛出一个异常,让事务失败
                throw new NullPointerException();
}
                ContentValues values =new ContentValues();
                values.put("name", "Game of Thrones");
                values.put("author", "George Martin");
                values.put("pages", 720);
                values.put("price", 20.85);
                db.insert("Book", null, values);
                db.setTransactionSuccessful();//事务已经执行成功
               

} catch (Exception e) {
e.printStackTrace();
}finally{
db.endTransaction();//结束事务
Toast.makeText(MainActivity.this, "替换成功", 10).show();


}
}




});




}// onCreate


}// class

MyDatabaseHelper

/**
 *SQLiteOpenHelper是用来创建数据库和表的
 *
 */


public class MyDatabaseHelper extends SQLiteOpenHelper {
/*
*autoincrement表示id列是自增长的
*integer表示整型
*real表示浮点
*text表示文本类型
*blob表示二进制类型

* */
public static final String CREATE_BOOK="create table Book(" +
                               "id integer primary key autoincrement," +
                               "author text," +
                               "price real," +
                               "pages integer," +
                               "name text)";
public static final String CREATE_CATEGORY="create table Category(" +
                               "id integer primary key autoincrement," +
                               "category_name text" +
                               "category_code integer)";
private Context mContext;


public MyDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
mContext=context;
}
    /**
     *这个方法在创建数据库的时候,系统只调用一次
     */
@Override
public void onCreate(SQLiteDatabase db) {
//数据库创建完成,同时创建book表
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext, "创建成功", Toast.LENGTH_LONG).show();

}



/**
* 要想执行这个方法只要在new MyDatabaseHelper(this, "BookStore.db", null, 1);
* 传入的版本号大于之前传的,系统就可以调用此方法
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
/*如果数据库中已经存在Book,Category的表了,就将这两张表删掉,然后调用onCreate();方法
* 重新创建,这里现将存在的表删掉,是因为如果在创建表示发现这张表已经存在了,就会直接报错
* */
}


}//class

如果没有明白,下载我的例子:

http://download.csdn.net/detail/zhaihaohao1/8325293






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值