预先填充的SQLite数据库上的CRUD操作

时间:2016-03-29 19:47:27

标签: java android sqlite

我已使用SQLite Asset Helper成功实现了预填充数据库,并使用此tutorial执行查询以列出表中对象的名称。但是我想在Android应用程序中添加CRUD函数来添加,删除和插入新对象。我怎么能这样做?

DatabaseOpenHelper.java

import android.content.Context;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "camera1.db";
private static final int DATABASE_VERSION = 1;

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


}

DatabaseAccess.java

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

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

public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;

/**
 * Private constructor to aboid object creation from outside classes.
 *
 * @param context
 */
private DatabaseAccess(Context context) {
    this.openHelper = new DatabaseOpenHelper(context);
}

/**
 * Return a singleton instance of DatabaseAccess.
 *
 * @param context the Context
 * @return the instance of DabaseAccess
 */
public static DatabaseAccess getInstance(Context context) {
    if (instance == null) {
        instance = new DatabaseAccess(context);
    }
    return instance;
}

/**
 * Open the database connection.
 */
public void open() {
    this.database = openHelper.getWritableDatabase();
}

/**
 * Close the database connection.
 */
public void close() {
    if (database != null) {
        this.database.close();
    }
}

/**
 * Read all quotes from the database.
 *
 * @return a List of quotes
 */
public List<String> getQuotes() {
    List<String> list = new ArrayList<>();
    Cursor cursor = database.rawQuery("SELECT cameraname FROM camera", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        list.add(cursor.getString(0));
        cursor.moveToNext();
    }
    cursor.close();
    return list;
}
}

1 个答案:

答案 0 :(得分:0)

为此,您需要将数据库复制到设备中:

private static void copyDatabase(Context context) throws IOException {
    InputStream myInput = context.getResources().openRawResource(
            R.raw.database);
    String outFileName = getFullDbName(context);
    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

然后像往常一样打开数据库:

mSqlite = new SqliteHelper(context, getFullDbName(context), null,
            DATABASE_VERSION);

之后,您可以编写所需的任何原始查询。