简体   繁体   English

在Android中使用SQLite获取RowID

[英]Using SQLite in Android to get RowID

I am creating an app to record assignments for different classes. 我正在创建一个应用程序来记录不同类的作业。 Each class has it's own unique ID so the assignments listed for each class don't overlap into other classes. 每个类都有自己唯一的ID,因此为每个类列出的赋值不会与其他类重叠。 Here is a method I made to find the rowid for a certain class. 这是我为某个类找到rowid的方法。

public int getIdFromClassName(String className){
    String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery(query, null);
    return res.getColumnIndex("id");
}

However, this always returns a value of -1. 但是,它始终返回值-1。

Any thoughts on what to change to return the proper rowid value? 有什么想改变以返回正确的rowid值?

EDIT: 编辑:

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(
            "create table " + CLASSES_TABLE_NAME + " " +
                    "(id integer primary key, " + CLASSES_COLUMN_NAME + " text)"
    );
    db.execSQL(
            "create table " + ASSIGNMENTS_TABLE_NAME + " " +
                    "(id integer primary key, " + ASSIGNMENTS_COLUMN_NAME + " text, " + ASSIGNMENTS_COLUMN_TOTAL_POINTS
                    + " INTEGER, " + ASSIGNMENTS_COLUMN_CLASS_ID + " INTEGER)");

}

Try this query below to create a new column name rowID : 请尝试以下查询来创建新的列名rowID

Cursor cursor= db.rawQuery("SELECT *,"+CLASSES_TABLE_NAME +".rowid AS rowID"+" FROM "+CLASSES_TABLE_NAME , null);

And after this query you can fetch the real rowid from the rowID column : 在此查询之后,您可以从rowID列中获取真正的rowid

while (cursor.moveToNext()) {
        long chatRow=cursor.getLong(
                cursor.getColumnIndexOrThrow("rowID"));
}

The column returned by your query is called rowid , so you will not find a column called id . 查询返回的列称为rowid ,因此您将找不到名为id的列。

Ensure that you use the same column name in the query and in the call to getColumnIndex . 确保在查询和getColumnIndex调用中使用相同的列名。

And the index of this column is always zero; 并且该列的索引始终为零; you also need to read the actual value from the column: 您还需要从列中读取实际值:

int colIndex = res.getColumnIndexOrThrow("rowid"); // = 0
if (res.moveToFirst()) {
    return res.getInt(colIndex);
} else {
    // not found
}

However, Android has an helper function that makes it much easier to read a single value: 但是,Android有一个辅助函数 ,可以更容易地读取单个值:

public int getIdFromClassName(String className){
    String query = "SELECT rowid" +
                   " FROM " + CLASSES_TABLE_NAME +
                   " WHERE " + CLASSES_COLUMN_NAME + " = ?;";
    SQLiteDatabase db = this.getReadableDatabase();
    return DatabaseUtils.longForQuery(db, query, new String[]{ className });
}

res.getColumnIndex("id") is going to get you the column index of the column with the name "id". res.getColumnIndex(“id”)将获取名称为“id”的列的列索引。 and since you are getting -1, it cant find it.. are you sure your id column is not "_id"? 并且因为你得到-1,它无法找到它..你确定你的id列不是“_id”吗?

To get this to work you should do something like this.. 为了让这个工作你应该做这样的事情..

res.getLong(res.getColumnIndex("_id"));

Cursor.getColumnIndex() Cursor.getColumnIndex()

Cursor.getLong() Cursor.getLong()

(I would recommend you use getLong() rather than getInt() because SQLite database ID's can get larger than int's). (我建议你使用getLong()而不是getInt(),因为SQLite数据库ID可以比int更大。)

public int getIdFromClassName(String className) {
        String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE "
                + CLASSES_COLUMN_NAME + " = '" + className + "'";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery(query, null);
        if (res != null) {
            if (res.moveToFirst()) {
                do {
                    return Integer.parseInt(res.getString(res.getColumnIndex("id"))); // if your column name is rowid then replace id with rowid
                } while (res.moveToNext());
            }
        } else {
            Toast.makeText(context, "cursor is null", Toast.LENGTH_LONG).show();
        }
    }

Check your Cursor if its null check your Log that your table is created successfully and if its not null make sure your table has column id in it. 检查您的Cursor是否为null,检查您的Log是否已成功创建表,如果它不为null,请确保您的表中包含列id

You can try this: 你可以试试这个:

public int getIdFromClassName(String className){
String query = "SELECT id FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
int id=-1;
If(res!=null&&res.moveToFirst())
id=res.getInt(res.getColumnIndex("id"));
return id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM