1

我正在开发一个需要我使用数据库的 Android 应用程序。读了一段时间后,我决定使用 SQLite 数据库,我开始阅读我应该如何使用它,但是每本书/教程/等等……都通过允许用户向其中添加信息来开发一个可更新的数据库。(如日记或运行时间记录应用程序样式)。我只需要创建(我的意思是,像硬编码)我的数据库并查询它。我的数据库将无法由用户更新。我很确定这应该是一种简单/虚拟的方法,但我还没有找到它。所以,如果有人可以帮助我,那就太棒了。;)

谢谢。阿美特。

4

2 回答 2

1

请查看以下链接: 使用 DAO 和 Content Provider 的 SQLite 数据库教程

您只需要 2 个类:

  • 数据库类(4.3. 数据库和数据模型):

公共类 MySQLiteHelper 扩展 SQLiteOpenHelper {

public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";

private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;

// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
        + TABLE_COMMENTS + "(" + COLUMN_ID
        + " integer primary key autoincrement, " + COLUMN_COMMENT
        + " text not null);";

    // Database creation sql statement
private static final String TABLE_CREATE = "CREATE TABLE tablename....."

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

@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);
    database.execSQL(TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // You don't need this. If you don't change the DATABASE_VERSION value then this method will not be called.
}

}

公共类 CommentsDataSource {

// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
        MySQLiteHelper.COLUMN_COMMENT };

public CommentsDataSource(Context context) {
    dbHelper = new MySQLiteHelper(context);
}

public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
}

public void close() {
    dbHelper.close();
}

public List<Comment> getAllComments() {
    List<Comment> comments = new ArrayList<Comment>();

    Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
            allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Comment comment = cursorToComment(cursor);
        comments.add(comment);
        cursor.moveToNext();
    }
    // Make sure to close the cursor
    cursor.close();
    return comments;
}

private Comment cursorToComment(Cursor cursor) {
    Comment comment = new Comment();
    comment.setId(cursor.getLong(0));
    comment.setComment(cursor.getString(1));
    return comment;
}

}

  • 但我建议您也检查一下内容提供程序示例(8.4. 创建 ContentProvider)。它一点也不复杂。
于 2012-06-14T20:13:29.310 回答
0

您可以使用 SQLiteOpenHelper 的 onCreate 方法来执行创建数据库所需的 sql。sql 可以是硬编码的,也可以是从文件中读取的。这样做可以让您在首次运行应用程序时初始化数据库。

另一种选择是使用SQLite 数据库浏览器等工具

这是一个桌面应用程序,可用于构建 sqlite 数据库。一旦你创建了它,你就必须决定如何部署它。我从来没有尝试过这样做,但我想你可以将它捆绑在你的资源文件夹中,然后在应用程序安装后首次运行时将其移动到正确的目录中。

于 2012-06-14T19:56:50.953 回答