热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用自动增量主键插入表中-Insertintotablewithautoincrementprimarykey

Imcreatingatableasfollows:我正在创建一个表如下:@OverridepublicvoidonCreate(SQLiteDatabasedb){

I'm creating a table as follows:

我正在创建一个表如下:

@Override
public void onCreate(SQLiteDatabase db) {
    String sql =
            "CREATE TABLE IF NOT EXISTS users (" +
                    "_id INTEGER PRIMARY KEY, " +
                    "name TEXT NOT NULL, " +
                    "password TEXT NOT NULL);";
    db.execSQL(sql);

    sql = "INSERT INTO users VALUES ('testuser', 'textpassword')";
    db.execSQL(sql);
}

But when I try to insert a user, I'm getting the following exception:

但是当我尝试插入用户时,我遇到以下异常:

android.database.sqlite.SQLiteException: table users has 3 columns but 2 values were supplied (code 1): , while compiling: INSERT INTO users VALUES ('testuser', 'textpassword')

android.database.sqlite.SQLiteException:表用户有3列但提供了2个值(代码1):,同时编译:INSERT INTO用户VALUES('testuser','textpassword')

As _id is the primarykey, why is it expecting it? I also tried AUTOINCREMENT but it doesn't work.

由于_id是主键,它为什么期待它?我也试过AUTOINCREMENT但它不起作用。

2 个解决方案

#1


3  

Try this

尝试这个

 @Override
public void onCreate(SQLiteDatabase db) {
String sql =
        "CREATE TABLE IF NOT EXISTS users (" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                "name TEXT NOT NULL, " +
                "password TEXT NOT NULL);";
db.execSQL(sql);

sql = "INSERT INTO users(name, password) VALUES ('testuser', 'textpassword')";
db.execSQL(sql);
}

AUTOINCREMENT NOT NULL is missing in your insert query which will increase the value of _id field automatically.

#2


2  

You should specify the values you're inserting:

您应该指定要插入的值:

sql = "INSERT INTO users(name, password) VALUES ('testuser', 'textpassword')";

There's no need to specify AUTOINCREMENT: On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use. This is true regardless of whether or not the AUTOINCREMENT keyword is used.

不需要指定AUTOINCREMENT:在INSERT上,如果未明确给出ROWID或INTEGER PRIMARY KEY列的值,则它将自动填充未使用的整数,通常比当前使用的最大ROWID多一个。无论是否使用AUTOINCREMENT关键字,都是如此。


推荐阅读
author-avatar
靈幻雪月
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有