以格式row [field] - >格式从数据库中读取数据值

时间:2013-10-15 11:16:15

标签: android

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

我有这个数据库:

表名:文章 字段: ID 文章 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;
}

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

e.g。 行[文章] 并获取文章的,并从同一查询获取行[id]并获取id字段中的值。

1 个答案:

答案 0 :(得分: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();

    }