【问题标题】:Using the WHERE clause in SQLite在 SQLite 中使用 WHERE 子句
【发布时间】:2013-05-30 05:11:55
【问题描述】:

我有一个关于在 SQLite 中使用 WHERE 子句的一般性问题。我已经使用过一些 SQLite 并且知道我的方式。但是,我在使用 WHERE 子句时遇到了问题。

我有一个 Android 应用程序,我需要在其中使用 SQLite WHERE 子句执行一些简单的操作。然而,尽管整天都在试验 WHERE 子句,但我还是一无所获。我正在尝试执行非常简单的 SQLite 命令(例如 SELECT name FROM tablename WHERE _id=2DELETE FROM tablename WHERE name='somename')。但是,每次我使用 where 子句时,要么返回 0 行(在 SELECT 的情况下),要么删除 0 行。

表名正确。列名是正确的。 (只要我没有指定 WHERE 子句,我在选择或插入时就没有遇到任何问题。)我确保查询/语句的格式正确。我已经尝试了原始查询/语句以及Android中SQLiteDatabase类提供的方法(我确保对SELECT和DELETE使用正确的方法{例如rawQuery()query() for SELECT}),但没有任何效果

我只需要能够使用 WHERE 子句执行简单的查询/语句。有人对正在发生的事情有任何见解吗?

这是创建我正在使用的表的代码:

public static final String TABLE_WORKOUTS = "workouts"

public static final String W_ID = "_id";
public static final String W_WORKOUT_NAME = "workout_name";
public static final String W_EXERICSE_NAME = "exercise_name";
public static final String W_EXERCISE_SETS = "exercise_sets";
public static final String W_EXERCISE_FIRST_ATTRIBUTE = "first_attribute";
public static final String W_EXERCISE_SECOND_ATTRIBUTE = "second_attribute";
public static final String W_EXERCISE_TYPE = "exercise_type";

private static final String createTableWorkouts = "CREATE TABLE " + TABLE_WORKOUTS + " (" + W_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
        W_WORKOUT_NAME + " TEXT, " + W_EXERICSE_NAME + " TEXT, " + W_EXERCISE_SETS + " TEXT, " +
        W_EXERCISE_FIRST_ATTRIBUTE + " TEXT, " + W_EXERCISE_SECOND_ATTRIBUTE + " TEXT, " + W_EXERCISE_TYPE + " TEXT);";

查询示例: String workoutName = "Some Workout"; Cursor cursor = datasource.executeRawQuery("SELECT * FROM " + WorkoutDatabase.TABLE_WORKOUTS + " WHERE " + WorkoutDatabase.W_EXERICSE_NAME + "='" + workoutName + "'", null);

示例记录(_id、锻炼名称、锻炼名称、套数、第一属性、第二属性、锻炼类型): 23、上身、卧推、5、160、5、体重

【问题讨论】:

  • 您的表定义没有问题。显示一些示例查询,以及您打算匹配的一些示例记录。
  • @CL。我提供了您要求的代码和示例。
  • exercise_name 列中的值为Bench Press,但您正在尝试将其与Some Workout 匹配。
  • @CL。哇!我不敢相信我做到了。我确实在这个问题上花了好几个小时。非常感谢!如果你把它作为答案,我会接受它。再次感谢!

标签: android sql sqlite android-sqlite


【解决方案1】:

这是一个可行的来源,它将使用 where 条件从 SQLite 数据库中检索值列表。通过使用游标,检索值并添加到 POJO 类中。我认为这段代码会对你有很大帮助。

public List<RationNamesPOJO> fetchRationMembers(String rationNumber) {

    ArrayList<RationNamesPOJO> RationDet = new ArrayList<RationNamesPOJO>();

    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cur = db.rawQuery("SELECT * FROM " + TABLE_NAME + " where " + PEOPLE_RATION_NUMBER + "='" + rationNumber + "'", null);

    if (cur.moveToFirst()) {
        do {

            RationNamesPOJO rationPojo = new RationNamesPOJO();
            rationPojo.setPeople_rationNumber(cur.getString(cur.getColumnIndex(PEOPLE_RATION_NUMBER)));
            rationPojo.setPeople_aadhaarNumber(cur.getString(cur.getColumnIndex(PEOPLE_AADHAAR_NUMBER)));
            rationPojo.setPeopleName(cur.getString(cur.getColumnIndex(PEOPLE_NAME)));
            rationPojo.setPeopleBiometric(cur.getString(cur.getColumnIndex(PEOPLE_FINGER_IMAGE)));

            RationDet.add(rationPojo);

        } while (cur.moveToNext());
    }

    return RationDet;

}

【讨论】:

    【解决方案2】:

    exercise_name 列中的值为Bench Press,但您正在尝试将其与Some Workout 匹配。

    【讨论】:

      【解决方案3】:

      你可以这样试试。

      实现 1

      String sqlQuery = "select * from Appointment where start_date='"
                      + startDate + "' order by start_date,time(start_date) ASC";
      
              cursor = getReadableDatabase().rawQuery(sqlQuery, null);
              // Log.e("Appointment ->","Total rows fetched for date "+
              // startDate+" "+cursor.getCount());
              if (cursor != null && cursor.moveToFirst()) {
                  do {
      
                  } while (cursor.moveToNext());
      

      }

      实现 2

      private boolean isRequestExists(int requestId) {
          Cursor cursor = null;
          boolean result = false;
          try {
              String[] args = { "" + requestId };
              StringBuffer sbQuery = new StringBuffer("SELECT * from ").append(
                      TABLE_NAME).append(" where _id=?");
              cursor = getReadableDatabase().rawQuery(sbQuery.toString(), args);
              if (cursor != null && cursor.moveToFirst()) {
                  result = true;
              }
          } catch (Exception e) {
              Log.e("Requestdbhelper", e.toString());
          }
          return result;
      }
      

      【讨论】:

      • 非常感谢代码建议!不幸的是,这基本上就是我一直在做的事情。不过感谢您的帮助!
      • @srikanth_gr 不。没有例外。只是没有结果。
      【解决方案4】:

      你好,你可以试试这个帮助类

                  Cursor cur1 = null, cur2 = null;
                  if (mySQLiteAdapter == null || !mySQLiteAdapter.isOpen()) {
                      mySQLiteAdapter = new SqliteAdapter(
                              LoginActivity.this);
                  }
      
                  try {
                      cur1 = mySQLiteAdapter
                              .executeSQLQuery(
                                      "select ifnull(max(login_id),0) as userCount from  table_login",
                                      null);
      
                      for (cur1.moveToFirst(); !(cur1.isAfterLast()); cur1
                              .moveToNext()) {
                          userCount = cur1.getString(cur1
                                  .getColumnIndex("userCount"));
      
                      }
                  } catch (Exception ex) {
                      Log.w("error while retrieving cursor values", ex.toString());
                  } finally {
                      cur1.close();
                      if (mySQLiteAdapter != null || mySQLiteAdapter.isOpen()) {
                          mySQLiteAdapter.close();
                      }
                  }
      

      ============================================

      这是你的助手类

         public Cursor executeSQLQuery(String sql, String[] selectionArgs) {
          Cursor cursor = null;
          try {
              if (database != null) {
                  cursor = database.rawQuery(sql, selectionArgs);
              }
          } catch (SQLiteException sqle) {
              Toast.makeText(context,
                      "Unable to execute sql query \n" + sqle.getMessage(),
                      Toast.LENGTH_SHORT).show(); 
          }
          return cursor;
      }
      

      【讨论】:

      • 好的,我现在就试试。我会让你知道我得到了什么。
      • 然后从 ddms-file explorer 中从您的应用程序中提取数据库,并查看您的表中是否有记录
      • 它就在那里。我已经选择并打印了好几次。如果我使用没有 where 子句的选择,它可以正常工作。但是,当我在其中添加 where 子句时,它就不起作用了。
      • 请问您在where子句中使用的是哪一列及其类型。我需要查询和表结构的朋友
      • 作为您使用的字符串,请在列的 where 子句中使用单引号 ('')。例如:SELECT name FROM tablename WHERE _id='2'
      猜你喜欢
      • 1970-01-01
      • 2017-04-14
      • 2022-06-14
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多