SQL游标错误

时间:2011-06-30 21:41:45

标签: android sql cursor

我一直在使用记事本SQLhelper(notesDBadapter)作为模型,其中一些有效,有些则无效。我可以为'fetchallrecords()获取一个游标,但如果我尝试调用传递参数并使用'WHERE',它会崩溃。传递参数但游标失败。我的活动代码;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listselectedfile);    

    //Button ID clicked in previous activity
    Bundle bundle = getIntent().getExtras();
    int BtnId = bundle.getInt("ButtonID");
    Toast.makeText(this, "ButtonID selected in Main:= " + BtnId, Toast.LENGTH_LONG) .show(); 

    mDbHelper = new SectionsDbAdapter(this);
    mDbHelper.open();
    fillData();

}  
    private void fillData() {
        // Get all of the notes from the database and create the item list
        //Cursor c = mDbHelper.fetchAllRecords();       <=== works fine
        Cursor c = mDbHelper.fetchRecordsbySource("UK"); <=== fails in DBhelper
        startManagingCursor(c);

        String[] from = new String[] { SectionsDbAdapter.KEY_DESC };
        //String[] from = new String[] { SectionsDbAdapter.KEY_SOURCE }; <=== can fetch this column from table
        int[] to = new int[] { R.id.tv_full_width };  //the R.id.xxx= view in the .xml file

        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter records =
            new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to);  //the .xml file containing the R.id.xxxx
        setListAdapter(records);
    }

在DBhelper中; 此调用有效并返回完整的表格;

    public Cursor fetchAllRecords() {

    return mDb.query(DATABASE_TABLE, new String[] {
    KEY_ROWID, KEY_DESC, KEY_DEPTH, KEY_TWEB, 
    KEY_BF1, KEY_TF1, KEY_BF2, KEY_TF2, 
    KEY_IMAJOR, KEY_IMINOR, 
    KEY_PLMAJOR, KEY_PLMINOR, 
    KEY_JTORSION, KEY_AREA,  
    KEY_WARPING, KEY_CYCHANNEL, 
    KEY_SHAPE, KEY_SOURCE, 
    KEY_UNITS},null, null, null, null, null);
}

此调用在游标上失败(参数成功传递);

    public Cursor fetchRecordsbySource(String source) throws SQLException {
    Log.v("In fetchRecordsbySource", "source = " +source);      

    Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {
    KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = " + source, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

在Eclipse调试中没有什么是明显的,但是,作为一个新手,我可能没有必要的观点。

有人能发现错误吗?

1 个答案:

答案 0 :(得分:0)

在您拥有的代码中,如果source是非数字值,则需要用单引号括起来,如下所示:

KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = '" + source + "'", null, null, null, null, null)

但如果你将过滤器参数传递给你,你会更好吗?这避免了(除其他外)SQL注入攻击

KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = ?", new String[] { source }, null, null, null, null)