android - 我应该在我的 Android 应用程序中使用什么数据库方法

标签 android database sqlite

我正在创建一个 Android 应用程序,我需要在其中使用 SQLite 存储数据。它需要存储日期、两个日期之间的天数和一些文本字段。我在网上查找了一些教程,我最满意的方法是这里的方法:

public class DataHelper {

private static final String DATABASE_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "table1";

private Context context;
private SQLiteDatabase db;

private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
  + TABLE_NAME + "(name) values (?)";

public DataHelper(Context context) {
  this.context = context;
  OpenHelper openHelper = new OpenHelper(this.context);
  this.db = openHelper.getWritableDatabase();
  this.insertStmt = this.db.compileStatement(INSERT);
}

public long insert(String name) {
  this.insertStmt.bindString(1, name);
  return this.insertStmt.executeInsert();
}

public void deleteAll() {
  this.db.delete(TABLE_NAME, null, null);
}

public List<String> selectAll() {
  List<String> list = new ArrayList<String>();
  Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
    null, null, null, null, "name desc");
  if (cursor.moveToFirst()) {
     do {
        list.add(cursor.getString(0));
     } while (cursor.moveToNext());
  }
  if (cursor != null && !cursor.isClosed()) {
     cursor.close();
  }
  return list;
}

private static class OpenHelper extends SQLiteOpenHelper {

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

  @Override
  public void onCreate(SQLiteDatabase db) {
     db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     Log.w("Example", "Upgrading database, this will drop tables and recreate.");
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
     onCreate(db);
  }
}
}

很抱歉这段代码很长。我不确定这种使用数据库的方式是否正确

最佳答案

  • DataHelper 的使用方向是正确的。使用 DataHelper 来创建数据库和表是一个不错的计划。但是,让您的 DataHelper 扩展 SQLiteOpenHelper 类,使其成为真正的 Helper 类。
  • 此外,最好将您创建的每个表分成不同的 Java 类。然后让您的 DataHelper 只需调用这些表/类的 onCreate 方法。
  • 此外,Android 还提供了一个 ContentProvider 来帮助您提供对数据的访问。尝试严格通过您自己的 ContentProvider 提供对数据库的访问。这提供了更好的灵活性和几个抽象级别。

以下是我最近使用过的一些示例。这些也来自另一个来源,但稍作修改。我不确定我从哪里得到原始的东西。但这是我从我正在做的事情中得到的。

希望这有帮助!

//SimpleNotesDBHelper (Your `DataHelper`)
public class SimpleNotesDBHelper extends SQLiteOpenHelper {

    private static final String NOTES_DATABASE_NAME = "simplenotes.db";
    private static final int DB_VERSION = 1;

    public SimpleNotesDBHelper(Context context) {
        super(context, NOTES_DATABASE_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        NotesTable.onCreate(db);
    }

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

}

//NotesTable (a seperate table in my db)
public class NotesTable {

    public static final String NOTES_TABLE = "notes";
    public static final String COL_ID = "_id";
    public static final String COL_CATEGORY = "category";
    public static final String COL_SUMMARY = "summary";
    public static final String COL_DESCRIPTION = "description";
    public static final String NOTES_TABLE_CREATE = "create table "
            + NOTES_TABLE
            + "("
            + COL_ID
            + " integer primary key autoincrement, "
            + COL_CATEGORY
            + " text not null, "
            + COL_SUMMARY
            + " text not null, "
            + COL_DESCRIPTION
            + " text not null"
            + ");";

    public static void onCreate(SQLiteDatabase database) {
        database.execSQL(NOTES_TABLE_CREATE);

        insertingSomeTestData(database);
    }

    public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        database.execSQL("drop table if exists " + NOTES_TABLE);
        onCreate(database);
    }
}

//SimpleNotesContentProvider (a ContentProvider to my db)
public class SimpleNotesContentProvider extends ContentProvider {

    private SimpleNotesDBHelper databaseHelper;

    private static final int SIMPLE_NOTES = 10; //arbitrary
    private static final int SIMPLE_NOTE_ID = 20; //arbitrary

    private static final String AUTHORITY = "ashton.learning.projects.simplenotes.contentprovider";
    private static final String BASE_PATH = "simplenotes";
    private static final String DIR_BASE_TYPE = "simplenotes";
    private static final String ITEM_BASE_TYPE = "simplenote";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
    public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + DIR_BASE_TYPE;
    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + ITEM_BASE_TYPE;
    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);      

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {

        int uriType = sURIMatcher.match(uri);

        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        int rowsDeleted = 0;
        switch (uriType) {
        case SIMPLE_NOTES:
            rowsDeleted = db.delete(NotesTable.NOTES_TABLE, selection, selectionArgs);
            break;
        case SIMPLE_NOTE_ID:
            String id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = db.delete(NotesTable.NOTES_TABLE, 
                        NotesTable.COL_ID + "=" + id, 
                        null);
            }
            else {
                rowsDeleted = db.delete(NotesTable.NOTES_TABLE, 
                        NotesTable.COL_ID + "=" + id + " and " + selection, 
                        selectionArgs);
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {

        int uriType = sURIMatcher.match(uri);

        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        int rowsDeleted = 0;
        long id = 0;
        switch(uriType) {
        case SIMPLE_NOTES:
            id = db.insert(NotesTable.NOTES_TABLE, null, values);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse(BASE_PATH + "/" + id);
    }

    @Override
    public boolean onCreate() {
        databaseHelper = new SimpleNotesDBHelper(getContext());
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, SIMPLE_NOTES);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", SIMPLE_NOTE_ID);
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {

        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(NotesTable.NOTES_TABLE);

        int uriType = sURIMatcher.match(uri);

        switch (uriType) {
        case SIMPLE_NOTES:
            break;
        case SIMPLE_NOTE_ID:
            queryBuilder.appendWhere(NotesTable.COL_ID 
                    + "="
                    + uri.getLastPathSegment());
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        SQLiteDatabase db = databaseHelper.getWritableDatabase();

        Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {

        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        int rowsUpdated = 0;

        switch (uriType) {
        case SIMPLE_NOTES:
            rowsUpdated = db.update(NotesTable.NOTES_TABLE, 
                    values, 
                    selection, 
                    selectionArgs);
            break;
        case SIMPLE_NOTE_ID:
            String id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsUpdated = db.update(NotesTable.NOTES_TABLE, 
                        values, 
                        NotesTable.COL_ID + "=" + id, 
                        null);
            }
            else {
                rowsUpdated = db.update(NotesTable.NOTES_TABLE, 
                        values, 
                        NotesTable.COL_ID + "=" + id + " and " + selection, 
                        selectionArgs);
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

}

关于android - 我应该在我的 Android 应用程序中使用什么数据库方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777753/

相关文章:

java - 重用套接字并检测何时需要重新建立

android - Google Play 服务中的 NodeAPI 如何工作?

database - 如何使用 Vertica Database Designer 创建特定于查询的投影?

javascript - MongoDB 索引 : String vs Int

database - RSQLite RS-DBI 驱动程序 : (error in statement: no such table: test)

java - 如何在 JRuby 中初始化 SQLite3 JDBC 驱动程序?

java - Android 安全异常 - 没有权限 ACCESS_NETWORK_STATE

android - 我们可以使用 React Native 在 Android 系统中运行简单的 shell 脚本吗?

sql-server - SQL Server 如何合并两个数据库?

sqlite - 如何从 SQLite 中设置参数?