如何从数据库中提取单行

时间:2011-02-12 21:35:54

标签: android sqlite

我目前有下面的代码,它工作正常,直到我实际尝试物理调用查询的数据。也可以给某人一个关于如何使用WHERE子句查询单个ID的示例。我试过了,但是在我甚至试图把任何东西拉回去之前,这会导致错误。

所有帮助都很合适。 最大

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"));

2 个答案:

答案 0 :(得分:4)

在尝试访问您的行之前,您需要在moveToFirst()上致电Cursor

答案 1 :(得分:1)

您可以按照以下方式检索值。

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());
                }
            }