【问题标题】:getting values from column in database从数据库中的列中获取值
【发布时间】:2013-09-12 23:07:02
【问题描述】:

我从数据库中的“threadid”列中获取值。问题是它从前一个记录/行中获取值。当我尝试获取第一条记录时,我的应用程序崩溃了,如何解决这个问题以及问题是什么?

long id;
long threadid = datasource.getthreadid(id);
Toast.makeText(getActivity(), String.valueOf(threadid), Toast.LENGTH_SHORT).show();

public long getthreadid(long id)
  {

      String ide=String.valueOf(id);
      String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID 
                + " FROM " + MySQLiteHelper.TABLE_NAME 
                + " WHERE " + MySQLiteHelper.COLUMN_ID + "=" + ide;
      Cursor cursor = database.rawQuery(queryz, null);
      cursor.moveToFirst();
     // cursor.moveToPosition(Integer.parseInt(String.valueOf(id)));
     long threadid= cursor.getLong(cursor.getColumnIndex("threadid"));

      cursor.close();
    return threadid;

  }

【问题讨论】:

    标签: android mysql sqlite android-cursor


    【解决方案1】:

    如果您只期待一排。那么做这样的事情可能会很有用。

    long threadid;
    
    if (cursor.moveToFirst())
    {
        threadid = cursor.getLong(cursor.getColumnIndex("threadid"));
    }
    else
    {
        // ah oh, we do not have this id!
        // do something here if you need to
    }
    

    另外,如果你要使用字符串,我建议你绑定参数。我知道你事先有很长一段时间,但对于字符串你可以这样做。

      String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID 
                + " FROM " + MySQLiteHelper.TABLE_NAME 
                + " WHERE " + MySQLiteHelper.COLUMN_ID + " = ?";
      Cursor cursor = database.rawQuery(queryz, new String[]{ide});
    

    【讨论】:

      【解决方案2】:

      要获取所有记录,您首先需要移动到第一个,然后遍历其余记录。

      if (cursor.moveToFirst()) {
          do {
              // get row values
          } while (cursor.moveToNext());
      }
      
      cursor.close();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 2011-09-21
        • 2022-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多