Sqlite:我如何修复pimary key autoincrement?

时间:2016-05-13 03:42:42

标签: android sqlite android-cursor

我有一个TOTALCOUNT表,其中一个名为COUNTID的PK _id列和一个名为CARDNUM的整数列。我在CARDNUM上插入,所以PK会自动增量。但是当我在Android Studio中进行LogCat输出时,第一次插入时显示_id = 1,第二次插入时显示_id = 1。我认为第二个插入应该显示_id = 2。

DBContract文件:

...
public static final String TABLE_NAME_TOTALCOUNT = "totalcount";
    public static final String COLUMN_NAME_COUNTID = "_id";
    public static final String COLUMN_NAME_CARDNUM = "cardnum";
    }
}

A second table, not shown is called USERINPUTS.

DBHelper文件:

public void onCreate(SQLiteDatabase db) {
    // Set up the Column headings for USERINPUTS and TOTALCOUNT Tables.
    db.execSQL(SQL_CREATE_ENTRIES);
    db.execSQL(SQL_CREATE_CARDNUM);
}

private static final String SQL_CREATE_CARDNUM =
        "CREATE TABLE IF NOT EXISTS " + DBContract.DBEntry.TABLE_NAME_TOTALCOUNT +
             "(" + DBContract.DBEntry.COLUMN_NAME_COUNTID +
                   " INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT, " +
                   DBContract.DBEntry.COLUMN_NAME_CARDNUM +
                   " INTEGER" + ")";

public void insertIntoTableTOTALCOUNT() {

    int cardnum = 0;
    // Get a reference to a writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    db.beginTransaction();

    ContentValues cv = new ContentValues();
    cv.put(DBContract.DBEntry.COLUMN_NAME_CARDNUM,cardnum);
    db.insert(DBContract.DBEntry.TABLE_NAME_TOTALCOUNT,null,cv);

    db.setTransactionSuccessful();
    db.endTransaction();
    // Close the database.
    if(db.isOpen())
        db.close();
}


Log.d("TAG", DatabaseUtils.dumpCursorToString(cursor));

1 个答案:

答案 0 :(得分:-1)

我尝试使用以下查询在SQLite(Firefox客户端)中创建一个表。它给了我一个错误

create table my_table (_id integer primary key not null autoincrement,name varchar(20)) 

试试这个

create table my_table (_id integer primary key autoincrement, name varchar(20))

并且您不需要将not null用于PK with Auto Increment,因为它永远不会为空。