我的表定义是:CREATE TABLE "Product"("ProID"INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "BarCode"VARCHAR NOT NULL UNIQUE , "ProductName"VARCHAR NOT NULL );
当我插入数据时,我遇到了这样的问题: 2011-03-25 15:43:08.792 BarCode12[6698:207] * -[sqlClass addRecord:] 断言失败,/Users/admin/Desktop/BarCode14copy/Classes/sqlClass.m:121 2011-03-25 15:43:08.793 BarCode12[6698:207] * 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“插入数据时出错。 '约束失败'' ...
写的代码是:- (void) addRecord:(NSMutableDictionary *)recordDict {
if(addStmt == nil) {
const char *sql = "insert into Product(ProID, BarCode , ProductName ) Values(?,?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
NSInteger recordId = [[recordDict objectForKey:@"ProID"] intValue];
NSLog(@"%d",recordId);
sqlite3_bind_int(addStmt, 1,recordId);
sqlite3_bind_text(addStmt, 2, [[recordDict objectForKey:@"BarCode"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [[recordDict objectForKey:@"ProductName"] UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
sqlite3_last_insert_rowid
rowID = sqlite3_last_insert_rowid(database);
NSLog(@"last inserted rowId = %d",rowID);
sqlite3_reset(addStmt);
我也试过没有限制,但同样的问题会继续......
如果一致性被移除,那么它会显示“数据库锁定”错误。 我们如何消除此错误以及如何将数据插入数据库?
最佳答案
关于“约束失败”的部分表示您违反了约束。这意味着您的 Product
表具有 PRIMARY KEY、UNIQUE 或 FOREIGN KEY 约束,并且您正在插入违反这些约束的值。
- 对于 PRIMARY KEY 和 UNIQUE 约束:您要插入重复值。
- 对于 FOREIGN KEY 约束:您插入的值在引用的表/字段中没有对应的匹配项。
更新:当您有一个 INTEGER PRIMARY KEY AUTOINCREMENT 时,您不应在 INSERT 语句中指定 ProdID; SQLite 会自动生成它。因此,将您的插入语句更改为
INSERT INTO Product (BarCode , ProductName) Values (?,?)
因为你之后已经用
取回了它rowID = sqlite3_last_insert_rowid(database);
别忘了也移除绑定(bind)!
关于iphone - sqlite中的数据插入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5431126/