0

enter code here我正在尝试编写一个查询来提取我的 Android SQLite 数据库表中位置引用 =“字符串”的所有行。我在我的数据库助手类中使用以下代码:

public Cursor fetchComponentsForLocation(String locationRef) {
    Cursor mCursor =
            rmDb.query(true, LOCATIONS_TABLE, new String[] {
                    LOCATION_ID, RUN_LINK, AREA_LINK, INSPECTION_LINK, LOCATION_REF, RACKING_SYSTEM, COMPONENT, POSITION, RISK, ACTION_REQUIRED, NOTES_GENERAL, MANUFACTURER, TEXT1, TEXT2, TEXT3, TEXT4, NOTES_SPEC}, 
                    LOCATION_REF + "=" + locationRef, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
}

我在我的活动中这样称呼它:

    // Get a Cursor for the list items
    Cursor listComponentCursor = rmDbHelper.fetchComponentsForLocation(locationRef);
    startManagingCursor(listComponentCursor);           

    // set the custom list adapter     
    setListAdapter(new MyListAdapter(this, listComponentCursor)); 

然后在我的 ListAdapter 中使用它来填充我的列表视图。现在在我的其他活动中,当我根据 id(即 long)获取行时,此代码可以正常工作。当我尝试使用 String 时,出现以下错误:

Caused by: android.database.sqlite.SQLiteException: **no such column: g:** , while compiling: SELECT DISTINCT _id, run_link, area_link, inspection_link, location_reference, racking_system, component, position, risk, action_required, notes_general, manufacturer, text1, text2, text3, text4, notes_spec FROM location_table WHERE location_reference=g

如您所见,在这种情况下 String = 'g',但它似乎在寻找名为 'g' 的列而不是查看数据!

很困惑为什么这适用于长而不是字符串。一如既往的帮助表示赞赏。

4

4 回答 4

3

用这个改变你的:

String[] columns = {LOCATION_ID, RUN_LINK, AREA_LINK, 
                    INSPECTION_LINK, LOCATION_REF, RACKING_SYSTEM, COMPONENT,
                    POSITION, RISK, ACTION_REQUIRED, NOTES_GENERAL, MANUFACTURER, TEXT1, TEXT2, TEXT3, TEXT4, NOTES_SPEC};
String[] selection = LOCATION_REF + "= ?";

Cursor c = rmDb.query(true, LOCATIONS_TABLE, columns, selection, new String[] {locationRef},
                    null, null, null, null);

我建议您使用占位符。这种方式更清洁,更安全。

于 2012-10-09T09:54:48.190 回答
1

where 应该看起来像LOCATION_REF + "='" + locationRef + "'"查询中的字符串应该包含在''

于 2012-10-09T09:53:18.047 回答
1

我认为您在要搜索的字符串周围缺少几个单引号:

LOCATION_REF + "='" + locationRef+"'", null,
于 2012-10-09T09:53:26.940 回答
1

使用这条线

rmDb.query(true, LOCATIONS_TABLE, new String[] {
                LOCATION_ID, RUN_LINK, AREA_LINK, INSPECTION_LINK, LOCATION_REF, RACKING_SYSTEM, COMPONENT, POSITION, RISK, ACTION_REQUIRED, NOTES_GENERAL, MANUFACTURER, TEXT1, TEXT2, TEXT3, TEXT4, NOTES_SPEC}, 
                LOCATION_REF + "='" + locationRef+"'", null,
                null, null, null, null);

实际上LOCATION_REFif 是 type String,所以你需要把逗号放在那里。SQLite 约定。

于 2012-10-09T09:54:55.503 回答