安卓开发之数据库事务的使用

package com.lidaochen.test;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    private MyOpenHelper myOpenHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myOpenHelper = new MyOpenHelper(getApplicationContext());
    }

    public void click(View v)
    {
        // 获取数据库对象
        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        // 开启shiwu
        db.beginTransaction();
        try
        {
            db.execSQL("update info set money = money - 100 where name = ?", new Object[]{"张三"});
            db.execSQL("update info set money = money + 100 where name = ?", new Object[]{"李四"});
            // 给当前事务设置一个成功的标记
            db.setTransactionSuccessful();
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(), "服务器繁忙,请稍后再转!", Toast.LENGTH_SHORT).show();
        }
        finally
        {
            // 关闭事务
            db.endTransaction();
        }
    }
}
package com.lidaochen.test;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyOpenHelper extends SQLiteOpenHelper {
    public MyOpenHelper(Context context)
    {
        super(context, "lidaochen111.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("create table info (_id integer primary key autoincrement,name varchar(20),phone varchar(20),money varchar(20))");
        db.execSQL("insert into info ('name','phone','money') values ('张三','138888','2000')");
        db.execSQL("insert into info ('name','phone','money') values ('李四','139999','5000')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
    }
}

 

转载于:https://www.cnblogs.com/duxie/p/10913849.html

你可能感兴趣的:(安卓开发之数据库事务的使用)