AUTOINCREMENT无法正常工作

时间:2014-05-05 17:37:56

标签: android sqlite

我想创建一个包含1个预定义行的表。 所以,我在onCreate();

中添加了一行

以下是我的代码:

private static final String CREATE_CATEGORY_TABLE = "CREATE TABLE CATEGORYTABLE (_id INTEGER PRIMARY KEY AUTOINCREMENT, category_name VARCHAR(255));";

private static final String DROP_CATEGORY_TABLE = "DROP TABLE IF EXISTS CATEGORYTABLE";

private static final String INSERT_PREDEFINED_CATEGORY = "INSERT INTO CATEGORYTABLE VALUES('Category 1');";

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        try {
            db.execSQL(DROP_CATEGORY_TABLE);
            onCreate(db);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        try {
            db.execSQL(CREATE_CATEGORY_TABLE);
            db.execSQL(INSERT_PREDEFINED_CATEGORY); <-- error on this line 
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

错误讯息:

sqlite returned: error code = 1, msg = table CATEGORYTABLE has 2 columns but 1 values were supplied

Failure 1 (table CATEGORYTABLE has 2 columns but 1 values were supplied) on 0x287cb8 when preparing 'INSERT INTO CATEGORYTABLE VALUES('Home');'.

这是在表格中插入预定义行的正确方法吗? 请帮忙!

1 个答案:

答案 0 :(得分:2)

该表有2列,因此您需要提供2个值,或指定要插入的列名。变化

INSERT INTO CATEGORYTABLE VALUES('Category 1')

INSERT INTO CATEGORYTABLE VALUES(NULL, 'Category 1')

INSERT INTO CATEGORYTABLE(category_name) VALUES('Category 1')

对于它的价值,在onCreate()onUpgrade()中捕获异常也是一种不好的做法。如果出现问题,回调不应该正常返回。