1 package com.example.sqlitetransaction;
2
3 import android.app.Activity;
4 import android.content.ContentValues;
5 import android.database.Cursor;
6 import android.database.sqlite.SQLiteDatabase;
7 import android.os.Bundle;
8 import android.util.Log;
9 import android.view.Menu;
10 import android.view.MenuItem;
11
12 public class MainActivity extends Activity {
13 SQLiteDatabase db;
14
15 @Override
16 protected void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.activity_main);
19
20 MydbOpenHelper helper = new MydbOpenHelper(this, "count.db", null,1);
21 db = helper.getReadableDatabase();
22
23 //insert();
24 try {
25 update();
26 query();
27 }
28 finally{
29 db.close();
30 }
31
32 }
33 private void update(){
34 db.beginTransaction();
35 try{
36 ContentValues cv = new ContentValues();
37 cv.put("money", 7000);
38 db.update("user", cv, "id=1", null);
39
40 //int b = 1/0;
41
42 cv.clear();
43 cv.put("money", 11000);
44 db.update("user", cv, "id=2", null);
45 db.setTransactionSuccessful();
46 }catch(Exception e){
47
48 }finally{
49 db.endTransaction();
50 }
51
52 }
53 private void query(){
54 Cursor c = db.rawQuery("select * from user", null);
55
56 while(c.moveToNext()){
57 int id = c.getInt(c.getColumnIndex("id"));
58 String username = c.getString(c.getColumnIndex("name"));
59 String money = c.getString(c.getColumnIndex("money"));
60 Log.i("sqlitetransaction", id+","+username+","+money);
61 }
62 }
63 private void insert(){
64 ContentValues cv = new ContentValues();
65 cv.put("id", 1);
66 cv.put("name", "user1");
67 cv.put("money", 8000);
68 db.insert("user", null, cv);
69 cv.clear();
70
71 cv.put("id", 2);
72 cv.put("name", "user2");
73 cv.put("money", 10000);
74 db.insert("user", null, cv);
75 cv.clear();
76 }
77 }