“主键应该是唯一的SQLite”错误

时间:2012-09-05 18:47:39

标签: android sqlite

这是我的主要Activity,我正在做我的所有工作。我在创建SQLite数据库时遇到错误。

private final String DB_NAME = "pocketCloudlets";
private final String TABLE_NAME_1 = "Members";
long count = 0;
static final String userTable="user";

static final String userName = "User";
static final String userID = "_id";
static final String age ="age";
static final String gender = "gender";
static final String password = "password";
static final String email = "email";

// Creating Table for User Record  

protected static final String table1=(" CREATE TABLE IF NOT EXISTS " 
    + userTable + " ("
    + userID + " INTEGER PRIMARY KEY NOT NULL, "
    + userName + " VARCHAR ,"
    + age + " VARCHAR ,"
    + gender + " VARCHAR )");

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.main);

        ArrayList<String> results = new ArrayList<String>();
        SQLiteDatabase sampleDB = null;

        try {      
            sampleDB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
            sampleDB.execSQL(table1);

            sampleDB.execSQL("INSERT INTO " +
                userTable +
                " Values ('13','dawdaa','4','female');");

            Cursor c = sampleDB.rawQuery("SELECT _id,userName, age, gender FROM " +
                userTable + " ", null);
        } catch (Throwable t) {
            // completed by the editor of this question
            // the 'catch' part of the try-catch structure was NOT present
        }

3 个答案:

答案 0 :(得分:2)

我认为这是您第一次开始活动时的效果。现在您已经使用_id = 13插入了一行,现在,每次再次执行此操作时,您将反复创建相同的ID。

由于您已指定_id作为表的主键,因此不允许这样做 - 主键必须是唯一的。

答案 1 :(得分:0)

Cursor c = sampleDB.rawQuery("SELECT _id,userName, age, gender FROM " +
    userTable + " ", null);

表格中没有userName列,而是使用user列创建了表格。

改为使用:

Cursor c = sampleDB.rawQuery("SELECT _id, user, age, gender FROM " + userTable, null);

答案 2 :(得分:0)

尝试将userID列设置为Integer Primary Key AutoIncrement。我也很确定你不能在sqlite中使用VARCHAR - 你需要使用TEXT。请查看此链接以供参考:http://www.sqlite.org/datatype3.html