这个查询有问题吗?为什么不起作用?

时间:2019-11-21 14:38:27

标签: android database sqlite db-browser-sqlite

  public ArrayList<String> getQuietPlaces(String lng, String lat) {
        ArrayList<String> quietPlaces = new ArrayList<String>();
        SQLiteDatabase db = this.getReadableDatabase();
        String quietPlacesLocation = "SELECT (quietPlaceLongitude || \"/\" || quietPlaceLatitude) as locationCoordinates" +
                " FROM quietPlaces Where quietPlaceLongitude BETWEEN "
                 + lng +"-10 AND "
                 + lng + "+10 AND quietPlaceLatitude BETWEEN"
                + lat +"-10 AND "
                + lat + "+10";
        Cursor cursor = db.rawQuery(quietPlacesLocation, new String[]{lng, lat});

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String locationCoordinate = cursor.getString(cursor.getColumnIndex("locationCoordinates"));
                quietPlaces.add(locationCoordinate);
            }
        }
        return quietPlaces;
    }

这个想法是返回所有落在Y轴上+10或-10的位置,对于X轴也是如此。它确实可以在SQLBrowser上运行,但是在Android Studio上的声明可能不同。我是这个软件的新手。

1 个答案:

答案 0 :(得分:0)

由于您串联了变量lnglat的值,因此不能将它们作为rawQuery()的第二个参数传递,而必须传递null。
另外,如果将/括在单引号内,则无需使用和转义双引号:

String quietPlacesLocation = "SELECT (quietPlaceLongitude || '/' || quietPlaceLatitude) as locationCoordinates" +
        " FROM quietPlaces Where quietPlaceLongitude BETWEEN "
        + lng + "-10 AND "
        + lng + "+10 AND quietPlaceLatitude BETWEEN "
        + lat + "-10 AND "
        + lat + "+10";
Cursor cursor = db.rawQuery(quietPlacesLocation, null);


但是,推荐的传递参数lnglat的方法是使用?占位符并将其值(在您的情况下为4个值)作为rawQuery()的第二个参数传递

String quietPlacesLocation = "SELECT (quietPlaceLongitude || '/' || quietPlaceLatitude) as locationCoordinates" +
        " FROM quietPlaces Where quietPlaceLongitude BETWEEN "
        + ? + "-10 AND "
        + ? + "+10 AND quietPlaceLatitude BETWEEN "
        + ? + "-10 AND "
        + ? + "+10";
Cursor cursor = db.rawQuery(quietPlacesLocation, new String[] {lng, lng, lat, lat});