Android:数据库getInt()

时间:2016-11-15 10:42:22

标签: android sqlite

public void insert(View target){
    String mBirth = birth_year.getText().toString();
    String mName = name.getText().toString();
    String mHome = hometown.getText().toString();
    Toast.makeText(getApplicationContext(), mBirth+mName+mHome ,
            Toast.LENGTH_SHORT).show();
    db.execSQL("INSERT INTO member VALUES (null, '"+ mBirth + "', '"
            + mName + "', '" + mHome + "');");
    Toast.makeText(getApplicationContext(), "saved.",
            Toast.LENGTH_SHORT).show();
    birth_year.setText("");
    name.setText("");
    hometown.setText("");
}

public void search(View target){
    Cursor cursor;
    cursor = db.rawQuery("SELECT b_year, b_name, b_city FROM member;",null);
    String mBirth="Year\n", mName="Name\n", mHome="City\n";
    while(cursor.moveToNext()){
        int gBirth = cursor.getInt(0);
        String gName = cursor.getString(1);
        String gHome = cursor.getString(2);
        mBirth += (Integer.toString(gBirth)+'\n');
        mName += (gName+'\n');
        mHome += (gHome+'\n');
    }
    btext.setText(mBirth);
    ntext.setText(mName);
    htext .setText(mHome);
    Toast.makeText(getApplicationContext(), mBirth+mName+mHome ,
            Toast.LENGTH_SHORT).show();
}

我遇到的问题是数据库无法正常工作。 当我执行insert()时,它不会在birth_year Edit_Text上写任何内容,我希望db.execSQL()会抛出SQLiteException。 但是不会抛出异常,当我执行search()时,gBirth0result 结果显示在链接中。我想在执行insert() birth_year时没有写任何内容时抛出异常。 我该如何解决?

1 个答案:

答案 0 :(得分:0)

如果SQL字符串无效,

execSQL仅抛出异常。将其更改为insert,如果它返回-1则抛出您自己的异常或只使用insertOrThrow