【问题标题】:How does Cursor work in android [closed]光标在android中如何工作[关闭]
【发布时间】:2015-03-04 22:48:38
【问题描述】:

我很难在我的程序中准确地可视化“光标”功能。我有点明白它的意思,但谁能详细解释它的功能?

光标指的是Cursor 接口。 我无法简单地理解它在任何事物中所起的作用。

http://developer.android.com/reference/android/database/Cursor.html

【问题讨论】:

标签: java android cursor


【解决方案1】:

从 SQLite 数据库上的查询返回一个 Cursor 对象。 它将返回查询返回的所有行。

假设您的数据库数据库中有一个名为 names 的表,配置如下:

_id     _name
1       Space Ghost
2       Zorak
3       Moltar
4       Brak

如果你想从这个表中获取所有数据并使用它,你会这样做 像这样:

public HashMap<Integer, String> getNames(){

 HashMap<Integer, String> data = new HashMap<Integer, String>();

 try{
  SQLiteOpenHelper helper = new MyOpenDbHelper(context);
  SQLiteDatabase db = helper.getReadableDatabase();
  String selectQuery = "SELECT  * FROM names";
  Cursor cursor = db.rawQuery(selectQuery, null);
  if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
    do{
        int mID = cursor.getInt(0); //column 0 for the current row
        String mName = cursor.getString(1); //column 1 for the current row
        data.put(mID, mName);

      } while (cursor.moveToNext()); //move to next row in the query result

  }

 } catch (Exception ex) {
    Log.e("MyApp", ex.getMessage());
 } finally
 {
    if (cursor != null) {
       cursor.close();

    }
    if (db != null) {
        db.close();
    }

 }

return data;
}

通常您会创建自己的类来扩展 SQLiteOpenHelper,例如:

public class MyOpenDbHelper extends SQLiteOpenHelper {
     //........
}
【解决方案2】:

来自Wikipedia

在计算机科学中,数据库游标是一种控制结构,可以遍历数据库中的记录。游标有助于与遍历一起进行后续处理,例如数据库记录的检索、添加和删除。遍历的数据库游标特性使得游标类似于编程语言中迭代器的概念。

来自Here

游标是一种工具,可让您迭代集合中的记录。它有顺序和当前记录的概念。

来自The documentation you pointed yourself

提供对数据库查询返回的结果集的随机读写访问。

因此,不要将 Cursor 视为一种功能,而是一种从任何数据库以更有效的方式获取记录的方法。

【讨论】:

    【解决方案3】:

    你是指这个光标用法吗?

    public String databaseToString(){
        String dbString = "";
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
    
        //Cursor points to a location in your results
        Cursor c = db.rawQuery(query, null);
        //Move to the first row in your results
        c.moveToFirst();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多