首先,我来自西类牙,对我的语法感到抱歉。我正在将一些数据写入 sqlite 数据库,这是我的代码:
@try {
NSFileManager *fileMgr=[NSFileManager defaultManager];
NSString *dbPath=[[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:@"capturas.sqlite"];
BOOL succes=[fileMgr fileExistsAtPath:dbPath];
if(!succes)
{
NSLog(@"Cannot locate database '%@'.",dbPath);
}
if (!(sqlite3_open([dbPath UTF8String], &dbcapturas)==SQLITE_OK)) {
NSLog(@"An error has occured: %@",sqlite3_errmsg(dbcapturas));
}
//sqlite3_stmt *sqlStatement;
NSString *asd=numero.text;
NSString *insertStatement=[NSString stringWithFormat:@"INSERT INTO captura(key,tecnico, fecha,provincia,municipio,latitud,longitud,altura,familia,especie,numero,comentario)Values(\"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\")",asd,tecnico,fechaHora,tecnico,municipio,latitud,longitud,altura,tecnico,animal,asd,coment];
char *error;
if((sqlite3_exec(dbcapturas, [insertStatement UTF8String], NULL, NULL, &error))==SQLITE_OK)
{
NSLog(@"Person inserted.");
}
else
{
NSLog(@"Error: %s", error);
}
} @catch (NSException *exception) {
NSLog(@"fail");
}
@finally {
}
我第一次点击我得到的保存按钮:
2012-07-04 12:17:45.644 adasdasd[1783:f803] Person inserted.
第二次我得到:
2012-07-04 12:29:18.959 adasdasd[1840:f803] Error: column key is not unique
所以我的代码应该没问题,但是当我打开数据库时它完全是空的,知道吗?
最佳答案
您的主包中有 SQLITE 数据库文件。主包中的所有文件都是只读的。您需要将数据库复制到文档文件夹。
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@\"database_name.sql\"];
success = [fileManager fileExistsAtPath:writableDBPath];
// NSLog(@\"path : %@\", writableDBPath);
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@\"database_name.sql\"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success)
{
NSAssert1(0, @\"Failed to create writable database file with message '%@'.\", [error localizedDescription]);
}
}
关于ios - 将数据写入 sqlite xCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11327299/