我想获取一个学生的名字、中间名和姓氏,该学生的用户 ID 用于登录。我已经编写了这段特定的代码,但它停止了我的应用程序。
我也使用了 database.query() 和 .rawquery() 两种方式。
Cursor studentData(String userId) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
// Cursor cursor = db.rawQuery("select First_Name, Middle_Name, Last_Name from Student_Table where User_ID =?", new String[]{userId});
String data = cursor.getString(cursor.getColumnIndex("First_Name"));
db.close();
return cursor;
}
我应该在字符串中获取全名。
最佳答案
你有很多问题。
尝试使用
String data = cursor.getString(cursor.getColumnIndex("First_Name"));
, 将导致错误,因为您没有移动光标超出BEFORE THE FIRST ROW 并且尝试访问行-1 将导致异常(您可能遇到的问题)。- 你可以使用各种招式???方法例如moveToFirst、moveToNext(最常见的 2 个)、moveToLast、moveToPosition。
- 大部分光标移动???如果可以移动,方法返回 true,否则返回 false。
您不能关闭数据库然后访问游标(如果上述问题得到解决,就会发生这种情况)
游标缓冲行,然后仅在需要时缓冲。
也就是说,当从查询方法(或 rawQuery)返回的游标位于 BEFORE THE FIRST ROW (-1) 的位置时,它仅在尝试移动时才会出现通过 Cursor 填充 CursorWindow(缓冲区)(包括 getCount())并获取实际数据。所以数据库必须是打开的。
如果你想要一个字符串,全名,那么你可以使用 :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("First_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Middle_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Last_Name"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
或者交替:-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name"||" "||"Middle_Name"||" "||"Last_Name" AS fullname}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("fullname"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
- 底层查询是
SELECT First_Name||""||Middle_Name||""||LastName AS fullname FROM student_table;
所以你连接名字作为查询的一部分,它只动态返回一个创建了名为 fullname 的列。
关于android - 如何编写sqlite查询来获取特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55478582/