请帮我找出问题所在。
插入语句不起作用,当我检查保存在 /Users/jppangilinan/Library/Application Support/iPhone Simulator/4.3/Applications/61BBA03F-C240-414D-9A64-6CE3B34DF9C2/Documents/person.sqlite3 似乎保存在该位置的数据库没有任何表,这就是插入语句不起作用的原因。为什么它没有在我的项目的资源文件夹中复制我的 sqlite db? TIA
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent"person.sqlite3"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
[database beginTransaction];
NSString *query = [NSString stringWithFormat"insert into person(rowid,fname,lname,address) values (null, '%@','%@','%@')",fname.text,lname.text,address.text];
NSLog(@" %@",path);
NSLog(@" %@",query);
BOOL y= [database executeUpdate:query];
if (!y)
{
NSLog(@"insert failed!!");
}
NSLog(@"Error %d: %@", [database lastErrorCode], [database lastErrorMessage]);
[database commit];
[database close];
}
Best Answer-推荐答案 strong>
为了在应用程序的 Documents 文件夹中访问您的资源数据库,您首先需要在应用程序启动时将其复制到那里。
如果数据库文件在你的 xcode 项目的资源文件夹中,它不会自动复制到应用程序的文档目录中。
为此,您可以使用:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error;
NSString *databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent"person.sqlite3"];
[[NSFileManager defaultManager] copyItemAtPath:databasePath
toPath:[NSString stringWithFormat"%@/%@",documentsDirectory,@"person.sqlite3"]
error:&error];
您将能够使用现有代码访问现在位于文档文件夹中的数据库。
发生的情况是,由于没有复制现有的 DB 文件,当您调用 databaseWithPath 时会创建一个新的空文件,这就是您收到 Error 1: no 的原因这样的表:人 错误。
来自 FMDB documentation :
Database Creation
An FMDatabase is created with a path to a SQLite database file. This
path can be one of these three:
A file system path. The file does not have to exist on disk. If it
does not exist, it is created for you.
An empty string (@""). An empty database is created at a temporary location. This database is deleted with the FMDatabase connection is
closed.
NULL. An in-memory database is created. This database will be
destroyed with the FMDatabase connection is closed.
FMDatabase *db = [FMDatabase databaseWithPath"/tmp/tmp.db"];
关于ios - SQLite 使用 FMDB : Insert record not working/no such table ,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/8499588/
|