开发者

SQLite insert error "Constraint Failed"

I am having problems when inserting data into a sqlite table, I have read lots of posts but still not found any solution, hope you can help me.

My table definition is:

CREATE TABLE "forum_topics" ("id" INTEGER (11) PRIMARY KEY  NOT NULL  UNIQUE  DEFAULT 1, "id_user" INTEGER (11) NOT NULL  DEFAULT 0, "title" TEXT NOT NULL  DEFAULT None, "description" TEXT NOT NULL  DEFAULT None)

I am having that problem when executing the following function:

- (void)addTopic{
    if (addStmt == nil) {
        const char *sql = "INSERT INTO forum_topics (id_user, title, description) VALUES (?, ?, ?开发者_Python百科)";
        if (sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) {
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        }
    }
    sqlite3_bind_int(addStmt, 1, id_user);
    sqlite3_bind_text(addStmt, 2, [title UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(addStmt, 3, [desc UTF8String], -1, SQLITE_TRANSIENT);


    if (SQLITE_DONE != sqlite3_step(addStmt)) {
        NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
    }
    else {
        self._id = sqlite3_last_insert_rowid(database);
    }
    sqlite3_reset(addStmt);
    sqlite3_finalize(addStmt);
    addStmt = nil;
}

Well, I also tried to force binding the id column of the table, and it did not crash despite of the fact that id has PRIMARY KEY and UNIQUE constraints and it is supposed to be unsettable... Any suggestion? Thank you.


Can you tell us what error you are getting? Is you id_user variable is a real integer, if not then i = [id_user intValue];

Because there is an sql error column id is not unique when your inserting the row second time.

You are inserting the new record by specifying column name, but you are not specifying the value for 'id' column so it assume the default value 1, but which is already set to table when you insert the first record.

INSERT INTO forum_topics (id_user, title, description) VALUES (2,'A' , 'A'); //very first time

but when you are inserting second time you are not specifying the value for 'id' column and default value for this column is 1 (but it is already saved when you insert the record first time). so if you want to avoid you must specify the 'id' column value unique

INSERT INTO forum_topics (id,id_user, title, description) VALUES (2,2,'A' , 'A');// now this will insert the row successfully. Change the schema to

CREATE TABLE "forum_topics" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "id_user" INTEGER (11) NOT NULL  DEFAULT 0, "title" TEXT NOT NULL  DEFAULT None, "description" TEXT NOT NULL  DEFAULT None);


Check out that the string value, if it contains ', the query string wont be complete. Just replace ' with ''. If possible for you. shall you post the query string with the values to be stored?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜