在 SQLite 中显示具有给定 ID(SELECT WHERE 语句)的行不起作用 Android Studio
Displaying rows with given id (SELECT WHERE statement) in SQLite doesnt work Android Studio
我的 SqliteOpenHelper
class 中有这个方法:
public String getTablica(int id,Context context)
{
SQLiteDatabase db=this.getWritableDatabase();
String query="SELECT "+COL2+" FROM "+TABLE_NAME+" WHERE "+COL1+"="+id;
Cursor cursor=db.rawQuery(query,null);
try {
cursor.moveToFirst();
return cursor.getString(1);
}
catch(Exception ex)
{
Toast.makeText(context,ex.getMessage(),Toast.LENGTH_LONG).show();
return "";
}
}
我在 cursor.getString(1)
行收到此错误
我只想打印 ID 与函数参数中的 ID 匹配的第一行...但是我收到此错误,如何解决它以及我做错了什么?
来自docs:
getString (int columnIndex)
Returns the value of the requested column as a String.
The result and whether this method throws an exception when the column value is null or the column type is not a string type is implementation-defined.
Parameters
columnIndex
int: the zero-based index of the target column.
所以方法 getString()
参数索引从 0 开始。您正在请求索引为 1 的参数,它是第二列。
return cursor.getString(1);
由于您在 SELECT 语句中仅请求一列,而您正试图获取第二列,因此出现异常,这就是它失败的原因。
要修复它,将上一行更改为这一行:
return cursor.getString(0);
我的 SqliteOpenHelper
class 中有这个方法:
public String getTablica(int id,Context context)
{
SQLiteDatabase db=this.getWritableDatabase();
String query="SELECT "+COL2+" FROM "+TABLE_NAME+" WHERE "+COL1+"="+id;
Cursor cursor=db.rawQuery(query,null);
try {
cursor.moveToFirst();
return cursor.getString(1);
}
catch(Exception ex)
{
Toast.makeText(context,ex.getMessage(),Toast.LENGTH_LONG).show();
return "";
}
}
我在 cursor.getString(1)
行收到此错误
我只想打印 ID 与函数参数中的 ID 匹配的第一行...但是我收到此错误,如何解决它以及我做错了什么?
来自docs:
getString (int columnIndex) Returns the value of the requested column as a String.
The result and whether this method throws an exception when the column value is null or the column type is not a string type is implementation-defined.
Parameters
columnIndex int: the zero-based index of the target column.
所以方法 getString()
参数索引从 0 开始。您正在请求索引为 1 的参数,它是第二列。
return cursor.getString(1);
由于您在 SELECT 语句中仅请求一列,而您正试图获取第二列,因此出现异常,这就是它失败的原因。
要修复它,将上一行更改为这一行:
return cursor.getString(0);