我有一个应用程序,它根据5个文本字段中的信息将信息存储在数据库中。我无法对字段进行排序,甚至只能从一个字段中进行排序。另外,ORDER BY子句采用什么方法?数据库的代码片段如下:
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CONTENT = "Content";
public static final String lastName = "lastName";
public static final String firstName = "firstName";
public static final String school = "school";
public static final String email = "email";
public static final String intrest = "intrest";
Cursor d = sqLiteDatabase.rawQuery("SELECT * from " + MYDATABASE_TABLE + "ORDER BY " + lastName + " ASC" , null);
while (d.moveToNext()) {
int sort = d.getColumnIndex(lastName);
int sort2 = d.getColumnIndex(intrest);
String lastName = d.getString(sort);
String intrest = d.getString(sort2);
System.out.println("GOT STUDENT " + lastName + " LIKES " + intrest);
}
答案 0 :(得分:0)
尝试在代码中使用(cursor.getCount()> 0)方法和(cursor!= null)条件来检查是否获取数据。我已经在下面展示了。并尝试使用Log查询完美的查询,并将该查询放入sqlite数据库以检查它是否正常工作。
Cursor d = sqLiteDatabase.rawQuery("SELECT * from " + MYDATABASE_TABLE + " ORDER BY " + lastName + " ASC" , null); // here I have edited space before ORDER BY word starts. Please note this
Log.d("query",">>>>"+SELECT * from " + MYDATABASE_TABLE + " ORDER BY " + lastName + " ASC"); // check this query is going to right way or not using local database.
if(d != null){
if(d.getCount() > 0){ // to check you get one or more data
d.moveToFirst();
do{
int sort = d.getColumnIndex(lastName);
int sort2 = d.getColumnIndex(intrest);
String lastName = d.getString(sort);
String intrest = d.getString(sort2);
System.out.println("GOT STUDENT " + lastName + " LIKES " + intrest);
} while (d.moveToNext());
}
}
试试这个。希望它会对你有所帮助。
答案 1 :(得分:0)
我更喜欢查询方法,因为它更清晰:
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CONTENT = "Content";
public static final String lastName = "lastName";
public static final String firstName = "firstName";
public static final String school = "school";
public static final String email = "email";
public static final String interest = "interest";
public final String[] columns = new String[] {
lastName,
firstName,
school,
email,
interest
};
public void printInOrder(String column) {
Cursor d = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null, null, null, null, column + " ASC");
while (d.moveToNext()) {
int sort = d.getColumnIndex(lastName);
int sort2 = d.getColumnIndex(interest);
String lastName = d.getString(sort);
String interest = d.getString(sort2);
System.out.println("GOT STUDENT " + lastName + " LIKES " + interest);
}
}