开发者

How to pull a single row from a database

I currently have the code below it works fine up until I actually try to physically call the data queried. Also can someone given an example on how to query a single ID using a WHERE clause. I tried, but that开发者_Go百科 causes an error before I can even try to pull anything back out.

All help appriciated. Max

String questionval;
    String answer1val;
    String answer2val;
    private final String SAMPLE_DB_NAME = "QnA";
    private final String SAMPLE_TABLE_NAME = "friends";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SQLiteDatabase db;
        db =  this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);

        db.execSQL("CREATE TABLE IF NOT EXISTS " +
                SAMPLE_TABLE_NAME +
                " (ID INT(3), Questions VARCHAR, Answer1 VARCHAR," +
                " Answer2 VARCHAR, Answer3 VARCHAR," +
                " Answer4 VARCHAR, CorrectAnswer INT(1), Reason VARCHAR);");

        db.execSQL("INSERT INTO " +
                SAMPLE_TABLE_NAME +
                " Values ('1','" +
                "Question?'," +
                "'Answer1'," +
                "'Answer2'," +
                "'Answer3'," +
                "'Answer4'," +
                "'2'," +
                "'Reason');");

        Cursor c = db.rawQuery("SELECT * FROM " +
                SAMPLE_TABLE_NAME , null);


                    questionval = c.getString(c.getColumnIndex("Question"));
                    answer1val = c.getString(c.getColumnIndex("Answer1"));
                    answer2val = c.getString(c.getColumnIndex("Answer2"));


You need to call moveToFirst() on the Cursor before trying to access your row.


You can retrieve value as following.

Vector temp = null;

// Fetch the values from database
    Cursor c = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME,
                    null);

// Extract the values
            if (c != null) {

                if (c.moveToFirst()) {
                    do {

                        temp = new Vector();
// Title was the field(column) name of the  table
                    temp.addElement(c.getString(c.getColumnIndex("Title")));

// Description was the field(column) name of the table      
                        temp.addElement(c
                                .getString(c.getColumnIndex("Description")));

                    } while (c.moveToNext());
                }
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜