安卓SQLite异常:java.lang.IllegalArgumentException: column '_id'不存在。

3

我创建了一个包含以下列的Sqlite数据库:

static final String dbName="demoDB";
    static final String tableName="Employees";
    static final String colID="EmployeeID";

那么

public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE "+tableName+" ("+colID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
                colName+" TEXT, "+colAge+" Integer);");
    }

我希望按如下方式选择数据库中的所有记录并在网格视图中显示它们:
SQLiteDatabase db=this.getWritableDatabase();
         Cursor cur= db.rawQuery("Select "+colName+", "+colAge+" from "+tableName, new String [] {});

String [] from=new String []{DatabaseHelper.colName,DatabaseHelper.colAge};
            int [] to=new int [] {R.id.colName,R.id.colAge};
            SimpleCursorAdapter sca=new SimpleCursorAdapter(this,R.layout.gridrow,c,from,to);


        GridView grid=(GridView)findViewById(R.id.grid);
        grid.setAdapter(sca);

但我收到以下异常:
java.lang.IllegalArgumentException: column '_id' does not exist.

数据库表中没有名为“_id”的列。

这段代码有什么问题?

谢谢。


仅因为其他线程没有提供答案并不意味着这个问题不是重复的。 - Mark Ingram
6个回答

8
解决这个问题的方法是使用以下select语句:
``` select EmpId as _id ```
因为你说适配器需要一个名为_id的列。
谢谢。

4
当使用适配器时,您的表必须始终将主键列命名为 "_id"。
只需更改。
static final String colID="EmployeeID"; 

为了

static final String colID="_id"; 

欢呼!

1

1
尝试这种方式。
SELECT  _ID as _ID,_ID as _id , cont_type ,.... FROM  DATABASE_TABLE ;

When _ID only ,Message is column '_id' does not exist.
When _id only ,Message is column '_ID' does not exist.

0

我尝试使用小写的_id而不是大写的_ID解决了问题。请确保再次使用小写的_id重新创建数据库。

非常感谢。


0
如果你从assets文件夹中加载数据库:在将数据库表中的id更改为_id之后,如果你要从assets文件夹中加载它,那么你需要先卸载应用程序,否则你将使用旧的数据库。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接