我可以在其他类(不是MyDatabaseHelper,而不是MyDB)中添加android sqlite事务吗?

时间:2016-07-04 09:53:15

标签: java sqlite transactions

当我在Android应用程序中创建sqlite时,我制作了3个类。 首先是制作数据库和表的“MyDatabaseHelper.java”。 第二个是“MyDB.java”,它包含一些函数(插入,游标,更新,删除)。 第三个是“MyDBDefaultValues”,它使用“MyDB.java”中的insert函数创建默认值。

关键在于交易。 按照交易手册(Android Database Transaction), 我需要在“MyDB.java”中插入“db.beginTransaction()”,因为有SQLitebase。 但我在其他类(MyDBDefaultValues.java)中使用insert函数创建默认值。

作为结果,我不知道在我的代码中添加事务的位置。我知道如果我在“MyDB.java”中创建默认代码,我可以在“MyDB.java”中添加事务。 但我想分开“MyDB.java”和“MyDBDefaultValues.java”。请告诉我如何在我的代码中添加事务。

感谢先进。

下面是我的代码。

MyDatabaseHelper.java

public class MyDatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "Torticollis";

private static final int DATABASE_VERSION = 1;

// Database creation sql statement
private static final String DATABASE_CREATE = "create table Torticollis_Management(" +
        "_id integer primary key autoincrement, " +
        "date text not null, " +           // store date to text type and convert between formats using the built-in date and time functions
        "stretching1 text, " +
        "stretching2 text, " +
        "stretching3 text, " +
        "stretching4 text, " +
        "stretching5 text," +
        "today_pain integer);";

public MyDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

    Log.d("confirm", "this is first's god");
}

// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);
}

// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
    Log.w(MyDatabaseHelper.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
    database.execSQL("DROP TABLE IF EXISTS Torticollis_Management");
    onCreate(database);
}

}

MyDB.java

公共类MyDB {

private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;

public final static String Tor_TABLE = "Torticollis_Management"; // name of table
public final static String Tor_ID = "_id"; // id value for Torticollis
public final static String Tor_DATE = "date";  // date of Torticollis
public final static String Tor_STRETCHING1 = "stretching1"; // stretching1 of Torticollis
public final static String Tor_STRETCHING2 = "stretching2"; // stretching2 of Torticollis
public final static String Tor_STRETCHING3 = "stretching3"; // stretching3 of Torticollis
public final static String Tor_STRETCHING4 = "stretching4"; // stretching4 of Torticollis
public final static String Tor_STRETCHING5 = "stretching5"; // stretching5 of Torticollis
public final static String Tor_TODAY_PAIN = "today_pain"; // today_pain of Torticollis
                                                          // today_pain value's type is "String" but it's real type is "int"

/**
 *
 * @param context
 */
public MyDB(Context context){                   // why do I add this 'context'??
    dbHelper = new MyDatabaseHelper(context);
}

public long insert(String date, String stretching1, String stretching2, String stretching3,
                          String stretching4, String stretching5, int today_pain){
    database = dbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    // values.put(Tor_ID, id); // "id" don't need to insert because that's made "autoincrement".
    values.put(Tor_DATE, date);
    values.put(Tor_STRETCHING1, stretching1);
    values.put(Tor_STRETCHING2, stretching2);
    values.put(Tor_STRETCHING3, stretching3);
    values.put(Tor_STRETCHING4, stretching4);
    values.put(Tor_STRETCHING5, stretching5);
    values.put(Tor_TODAY_PAIN, today_pain);         // why do I have to inert "integer"'s today_pain value into "String"'s Tor_TODAY_PAIN?
    return database.insert(Tor_TABLE, null, values);
}

public Cursor cursor() {
    database = dbHelper.getReadableDatabase();
    String[] cols = new String[] {Tor_ID, Tor_DATE, Tor_STRETCHING1, Tor_STRETCHING2, Tor_STRETCHING3,
            Tor_STRETCHING4, Tor_STRETCHING5, Tor_TODAY_PAIN};
    Cursor mCursor = database.query(true, Tor_TABLE, cols, null, null, null, null, null, null);
    if (mCursor != null) {mCursor.moveToFirst();}
    return mCursor; // iterate to get each value.
}

public boolean update(String date, String stretching1, String stretching2, String stretching3,
                   String stretching4, String stretching5, int today_pain) {
    database = dbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    // values.put(Tor_ID, id); // "id" don't need to insert because that exist only for counting
    values.put("date", date);
    values.put("stretching1", stretching1);
    values.put("stretching2", stretching2);
    values.put("stretching3", stretching3);
    values.put("stretching4", stretching4);
    values.put("stretching5", stretching5);
    values.put("today_pain", today_pain);
    database.update("Torticollis_Management", values, "date = ?", new String[]{date});      // need to know this coding
    return true;
}

public Integer delete(String date) {
    database = dbHelper.getWritableDatabase();
    return database.delete("Torticollis_Management", "id = ?", new String[]{date});         // need to know this coding
}

}

MyDBDefaultValues.java

公共类MyDBDefaultValues {

MyDB mydb;

public MyDBDefaultValues(Context context){      // why do I have to write the word "context". what's the mean of "context"?

    mydb = new MyDB(context);
    insertDefaultValues();      // insert default values if there is no data.
}

public void insertDefaultValues() {

    Cursor cursor = mydb.cursor();
    cursor.moveToLast();
    int count = cursor.getCount();
    if(count > 0) {
        // do nothing
    } else {    // insert default values if there is no data.
        mydb.insert("2016-07-01", "X", "X", "X", "X", "X", 0);
        mydb.insert("2016-07-02", "X", "X", "X", "X", "X", 0);
        mydb.insert("2016-07-03", "X", "X", "X", "X", "X", 0);
        mydb.insert("2016-07-04", "X", "X", "X", "X", "X", 0);
    }
}

}

1 个答案:

答案 0 :(得分:0)

通常,您应该将事务放入最外层的函数中;这是正确的(多个DB操作然后是原子的),并且效率更高:

public void insertDefaultValues() {
    mydb.beginTransaction();
    try {
        if (mydb.cursor().getCount() == 0) {
            mydb.insert(...);
            ...
        }
        mydb.setTransactionSuccessful();
    } finally {
        mydb.endTransaction();
    }
}

这要求您为beginTransaction()类的MyDB等电话添加包装。