• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - SQLite 使用 FMDB : Insert record not working/no such table

[复制链接]
菜鸟教程小白 发表于 2022-12-12 18:30:17 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

请帮我找出问题所在。

插入语句不起作用,当我检查保存在 /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-推荐答案


为了在应用程序的 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap