0

我对 Android 中的数据库使用感到非常困惑。

我有这个数据库:

表名:articles 字段:id , article , chapterid

我目前有以下代码并在片段中使用它:

List<Comment> contents = ((MainActivity)getActivity()).connectRawQueryDB("database.sqlite", "SELECT * FROM articles WHERE chapterid = 1");

在我的 MainActivity

    public List<Comment> connectRawQueryDB(String DB_NAME, String RawQuery) {
        List<Comment> comments = new ArrayList<Comment>();

        Cursor cursor = database.rawQuery(RawQuery,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;
}

我需要的是对数据库进行查询,然后以下列格式输出值:

例如row[article]并获取 article 的,并从同一个查询中获取 row[id] 并获取 id 字段中的值。

4

1 回答 1

0

在您的 dbhandler 中添加此方法....

 public ArrayList<Comment> getCommentdata()
{
    //get db
    SQLiteDatabase db = getWritableDatabase();

    ArrayList<Comment> resultCommentList = new ArrayList<Comment>();

    String resultQuery = "select id, article, chapterid from "+YOUR_TABLE;

    Cursor cursor = db.rawQuery(resultQuery, null);
    if(cursor.moveToFirst())
    {
        do
        {
            Comment commentObject = new Comment();
            commentObject.setcommentUID(cursor.getInt(0));
            commentObject.setarticle(cursor.getString(1));
            commentObject.setChapterID(cursor.getInt(2));
            resultCommentList.add(commentObject);
        }
        while(cursor.moveToNext());
    }

    //close db
    if(db != null)
        db.close();

    return resultCommentList;
}

当你想检索数据时

 allComent = localDBHelper.getCommentdata();

     for(int i = 0; i < allComent .size(); i++)
{
       int id=allComment.get(i).getcommentUID();
       String =allComment.get(i).getarticle();
       int cid=allComment.get(i).getChapteID();

    }
于 2013-10-15T11:38:36.150 回答