gpt4 book ai didi

java - Android SQLite,如何将Cursor变成字符串?

转载 作者:行者123 更新时间:2023-12-01 19:14:14 26 4
gpt4 key购买 nike

假设我有这样的 helper :

public class SqlHelper extends SQLiteOpenHelper {

public SqlHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE MyTable (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT)");
db.execSQL("INSERT INTO MyTable (NAME, PLACE) VALUES('ANTHONY','USA')");
db.execSQL("INSERT INTO MyTable (NAME, PLACE) VALUES('BERIMOR','UK')");
db.execSQL("INSERT INTO MyTable (NAME, PLACE) VALUES('IVAN','RUSSIA')");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}


}

在我的主代码中我执行一个查询

    SqlHelper sqlHelper = new SqlHelper(this, "MyDataBase.db", null, 1);
SQLiteDatabase DB = sqlHelper.getReadableDatabase();

Cursor c = DB.query(
"MyTable" /* table */,
new String[] { "PLACE" } /* columns */,
"id = ?" /* where or selection */,
new String[] { "RUSSIA" } /* selectionArgs */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);

DB.close();

但我不确定那个光标是什么?难道不应该是一个数组之类的东西吗?如果是这样,我如何从中获取原始值(字符串)?像这样的查询应该返回“IVAN”。

谢谢!

编辑2:

这个( c.getCount() )仍然返回 0,即没有结果...嗯...也许那么助手有问题?

     Cursor c = DB.query(
"MyTable" /* table */,
new String[] { "NAME" } /* columns */,
"PLACE = 'RUSSIA'" /* where or selection */,
null /* selectionArgs */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);



Log.e("DB RETURNS", String.valueOf( c.getCount() ) );

最佳答案

The Cursor object returned by a query provides access to a recordset of results.

获得游标后,您必须迭代它才能获取值。在你的情况下,你会这样做——

if (cur.moveToFirst()) {
int placeColumn = cur.getColumnIndex("PLACE");
String place = cur.getString(placeColumn);
}

要根据 PLACE 的查询获取 NAME,您应该执行 PLACE = ?

 Cursor c = DB.query(
"MyTable" /* table */,
new String[] { "NAME" } /* columns */,
"PLACE = ?" /* where or selection */,
new String[] { "RUSSIA" } /* selectionArgs */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);

关于java - Android SQLite,如何将Cursor变成字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7420783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com