【问题标题】:Sqlite: how do I fix pimary key autoincrement?Sqlite:如何修复主键自动增量?
【发布时间】:2018-04-19 11:34:26
【问题描述】:

我有一个 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));

【问题讨论】:

    标签: android sqlite android-cursor


    【解决方案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,因为它永远不会为空。

    【讨论】:

    • 好的将删除并重试。
    • 不幸的是同样的结果。
    • 不仅删除..卸载应用程序并再次运行。因为表需要删除。
    • 相同的结果,因为.. SQLiteHelper onCreate 在您第一次运行您的应用程序时只被调用一次.. 所以卸载并重试。
    • 对不起,我应该更清楚。我卸载了应用程序,然后在 SQLiteOpenHelper 中增加了数据库版本,这样它就会创建一个新表。
    猜你喜欢
    • 2012-01-21
    • 2013-04-18
    • 1970-01-01
    • 2015-05-11
    • 2013-05-24
    • 1970-01-01
    • 2018-05-06
    • 2015-12-15
    • 1970-01-01
    相关资源
    最近更新 更多