我是iphone和sqlite的新手,并做了一些教程。
我创建了一个方法,将一些时态信息存储到我的数据库中。
现在,当我在我的应用程序的firstView控制器上时,我调用了该方法两次。它将数据存储在特定表中两次。现在我去了SecondViewController,在那里我在头文件中有一个新的sqlite3对象,我再次将该方法粘贴到SecondViewController中。现在,当我在Second ViewController上调用该方法时,它会给出以下错误:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error while inserting data. 'database is locked''
我的代码是:
-(void)storeTemp
{
SchoolFocusIPadAppDelegate *delegate = (SchoolFocusIPadAppDelegate *)[[UIApplication sharedApplication] delegate];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"sfocusDB.sqlite"];
if(sqlite3_open([path UTF8String], &databases) == SQLITE_OK){
//const char *sql = "select * from animal";
const char *sql = "insert into groups(id, groupid, name, desc , createdon,createdby) Values(?,?,?,?,?,?)";
sqlite3_stmt *add;
if(sqlite3_prepare_v2(databases, sql, -1, &add, NULL) == SQLITE_OK){
NSLog(@"Connection Successful");
NSLog(@"***Storing START on Database ***");
sqlite3_bind_text(add, 2, [[NSString stringWithFormat:@"Temp Group Dont Open"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(add, 3, [[NSString stringWithFormat:@"kjhasd"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(add, 4, [[NSString stringWithFormat:@"asdas"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(add, 5, [[NSString stringWithFormat:@"asdsa"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(add, 6, [[NSString stringWithFormat:@""] UTF8String], -1, SQLITE_TRANSIENT);
NSLog(@"***Storing END on Database ***");
if(SQLITE_DONE != sqlite3_step(add))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(databases));
else {
NSLog(@"YES THE DATA HAS BEEN WRITTEN SUCCESSFULLY");
}
}
sqlite3_finalize(add);
}
sqlite3_close(databases);
}
请帮帮我朋友。我真的被困了。
非常感谢
答案 0 :(得分:3)
here lots of chances to kill
1.if your id is not null in DB it will kill with constraint failed error
if you don't want to insert any value to id remove from list
like
const char *sql = "insert into groups( groupid, name, desc , createdon,createdby) Values(?,?,?,?,?)";
并更改数字1-5而不是2-6
答案 1 :(得分:0)
我在if / else之后遇到了sqlite3_close的一些问题(不知道为什么)但是当我把最终化和关闭调用在中时,if,它会解决。我开始跟踪每个打开和关闭的NSLog相同(编号,所以我知道哪一个是哪个),然后你可以看到DB打开哪一步(因此锁定)
答案 2 :(得分:0)
您是否已将数据库复制到可写doc-dir?
您的预备电话需要稍作修改:
来自if(sqlite3_prepare_v2(databases, sql, -1, &add, NULL) == SQLITE_OK){
至if(sqlite3_prepare_v2(databases, [sql UTF8String], -1, &add, NULL) == SQLITE_OK){
(但这就是database locked
)的原因。