FMDB官方文档的翻译

FMDB

这是个Sqlite( http://sqlite.org/)的Objective-C封装库。  

FMDB的邮件列表:

http://groups.google.com/group/fmdb (大多时候,国内无法访问该地址)

关于SQLite的问题列表:

http://www.sqlite.org/faq.html

由于FMDB是建立在SQLite的之上的,所以你至少也该把这篇文章从头到尾读一遍。与此同时,把SQLite的文档页 http://www.sqlite.org/docs.html 加到你的书签中。

自动引用计数(APC)还是手动内存管理呢?

两种都行,FMDB会在编译的时候知道你是用的哪一种,然后进行相应处理。

使用方法

FMDB有三个主要的类
FMDatabase - 表示一个单独的SQLite数据库。 用来执行SQLite的命令。
FMResultSet - 表示FMDatabase执行查询后结果集

FMDatabaseQueue - 如果你想在多线程中执行多个查询或更新,你应该使用该类。这是线程安全的。

数据库创建

创建FMDatabase对象时参数为SQLite数据库文件路径。该路径可以是以下三种之一:
文件路径。该文件路径无需真实存,如果不存在会自动创建。
空字符串(@"")。表示会在临时目录创建一个空的数据库,当FMDatabase 链接关闭时,文件也被删除。
NULL. 将创建一个内在数据库。同样的,当FMDatabase连接关闭时,数据会被销毁。
(如需对临时数据库或内在数据库进行一步了解,请继续阅读: http://www.sqlite.org/inmemorydb.html )


FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];


打开数据库

在和数据库交互 之前,数据库必须是打开的。如果资源或权限不足无法打开或创建数据库,都会导致打开失败。


if (![db open]) { 
    [db release];
    return; 
} 


执行更新

一切不是SELECT命令的命令都视为更新。这包括  CREATE, UPDATE, INSERT,ALTER, COMMIT, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE  (等)。简单来说,只要不是以SELECT开头的命令都是UPDATE命令。

执行更新返回一个BOOL值。YES表示执行成功,否则表示有那些错误 。你可以调用 -lastErrorMessage 和 -lastErrorCode方法来得到更多信息。

执行查询

SELECT命令就是查询,执行查询的方法是以 -excuteQuery开头的。
执行查询时,如果成功返回FMResultSet对象, 错误返回nil. 与执行更新相当,支持使用 NSError**参数。同时,你也可以使用 -lastErrorCode和-lastErrorMessage获知错误信息。
为了遍历查询结果,你可以使用while循环。你还需要知道怎么跳到下一个记录。使用FMDB,很简单实现,就像这样:

FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];

while ([s next]) {

//retrieve values for each record

}

你必须一直调用   -[FMResultSet next]   在你访问查询返回值之前,甚至你只想要一个记录:


FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
if ([s next]) { 
     int totalCount = [s intForColumnIndex:0];
}


FMResultSet  提供了很多方法来获得所需的格式的值:
  • intForColumn:
  • longForColumn:
  • longLongIntForColumn:
  • boolForColumn:
  • doubleForColumn:
  • stringForColumn:
  • dataForColumn:
  • dataNoCopyForColumn:
  • UTF8StringForColumnIndex:
  • objectForColumn:
这些方法也都包括 {type}ForColumnIndex 的这样子的方法,参数是查询结果集的列的索引位置。

你无需调用  [FMResultSet close]来关闭结果集, 当新的结果集产生,或者其数据库关闭时,会自动关闭。


关闭数据库

当使用完数据库,你应该 -close 来关闭数据库连接来释放SQLite使用的资源。

[db close];

事务

FMDatabase是支持事务的。(讲FMDatabaseQueue的时候会讲怎么用)

数据净化(数据格式化)

使用FMDB,插入数据前,你不要花时间审查你的数据。你可以使用标准的SQLite数据绑定语法。
INSERT INTO myTable VALUES (?, ?, ?)
SQLite会识别 “?” 为一个输入的点位符, 这样的执行会接受一个可变参数(或者表示为其他参数,如NSArray, NSDictionary,或va_list等),会正确为您转义。
你也可以选择使用命名参数语法。
INSERT INTO myTable VALUES (:id, :name, :value)
参数名必须以冒名开头。SQLite本身支持其他字符,当Dictionary key的内部实现是冒号开头。注意你的NSDictionary key不要包含冒号。
NSDictionary *argsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", nil]; 
[db executeUpdate:@"INSERT INTO myTable (name) VALUES (:name)" withParameterDictionary:argsDict];

而且,代码不能这么写(为什么?想想吧。)
[db executeUpdate:[NSString stringWithFormat:@"INSERT INTO myTable VALUES (%@)", @"this has " lots of ' bizarre " quotes '"]];
你应该:
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has " lots of ' bizarre " quotes '"];
提供给 -executeUpdate: 方法的参数都必须是对象。就像以下的代码就无法工作,且会产生崩溃。
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", 42];
正确有做法是把数字打包成 NSNumber对象
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:42]];
或者,你可以使用  -execute*WithFormat: ,这是NSString风格的参数
[db executeUpdateWithFormat:@"INSERT INTO myTable VALUES (%d)", 42];

-execute*WithFormat:  的方法的内部实现会帮你封装数据, 以下这些修饰符都可以使用: %@, %c, %s, %d, %D, %i, %u, %U, %hi, %hu, %qi, %qu, %f, %g, %ld, %lu, %lld, and %llu.  除此之外的修饰符可能导致无法预知的结果。 一些情况下,你需要在SQL语句中使用 % 字符,你应该使用 %%。

使用FMDatabaseQueue 及线程安全

在多个线程中同时使用一个FMDatabase实例是不明智的。现在你可以为每个线程创建一个FMDatabase对象。 不要让多个线程分享同一个实例,它无法在多个线程中同时使用。 若此,坏事会经常发生,程序会时不时崩溃,或者报告异常,或者陨石会从天空中掉下来砸到你Mac Pro.  总之很崩溃。
所以,不要初始化FMDatabase对象,然后在多个线程中使用。
请使用 FMDatabaseQueue,它是你的朋友而且会帮助你。以下是使用方法:
首先创建队列。
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
这样使用。
[queue inDatabase:^(FMDatabase *db) { 
          [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 
          [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 
          [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
          FMResultSet *rs = [db executeQuery:@"select * from foo"]; 
         while([rs next]) {
            … 
         } 
}];

像这样,轻松地把简单任务包装到事务里:
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) { 
        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 
        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 
        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; 
        if (whoopsSomethingWrongHappened) { 
                *rollback = YES; return; 
        }
        // etc… 
        [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; 
}];

FMDatabaseQueue  后台会建立系列化的GCD队列,并执行你传给GCD队列的块。这意味着 你从多线程同时调用调用方法,GDC也会按它接收的块的顺序来执行。谁也不会吵到谁的脚 ,每个人都幸福。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Title: iOS 8 App Development Essentials Author: Neil Smyth Length: 824 pages Edition: 1 Language: English Publisher: CreateSpace Independent Publishing Platform Publication Date: 2014-12-16 ISBN-10: 1505586410 ISBN-13: 9781505586411 iOS 8 App Development Essentials is the latest edition of this popular book series and has now been fully updated for the Swift programming language, the iOS 8 SDK and Xcode 6. Beginning with the basics, this book provides an outline of the steps necessary to set up an iOS development environment. An introduction to the architecture of iOS 8 and programming in Swift is provided, followed by an in-depth look at the design of iOS applications and user interfaces. More advanced topics such as file handling, database management, in-app purchases, graphics drawing and animation are also covered, as are touch screen handling, gesture recognition, multitasking, iAds integration, location management, local notifications, camera access and video and audio playback support. Other features are also covered including Auto Layout, Twitter and Facebook integration, App Store hosted in-app purchase content, collection views, Sprite Kit-based game development, local map search and user interface animation using UIKit dynamics. The key new features of the iOS 8 SDK and Xcode 6 are also covered, including Swift playgrounds, universal user interface design using size classes, app extensions, Interface Builder Live Views, embedded frameworks, CloudKit data storage and TouchID authentication. The aim of this book is to teach the range of skills necessary to build apps for iOS 8. iOS 8 App Development Essentials takes a modular approach to the subject of iOS 8 application development for both the iPhone and iPad, with each chapter covering a self contained topic area consisting of detailed explanations, examples and step-by-step tutorials. This makes the book both an easy to follow learning aid and an excellent reference resource. Table of Contents Chapter 1. Start Here Chapter 2. Joining the Apple iOS Developer Program Chapter 3. Installing Xcode 6 and the iOS 8 SDK Chapter 4. A Guided Tour of Xcode 6 Chapter 5. Testing Apps on iOS 8 Devices with Xcode 6 Chapter 6. An Introduction to Swift Playgrounds Chapter 7. Swift Data Types, Constants and Variables Chapter 8. Swift Operators and Expressions Chapter 9. Swift Flow Control Chapter 10. The Swift Switch Statement Chapter 11. An Overview of Swift Functions and Closures Chapter 12. The Basics of Object Oriented Programming in Swift Chapter 13. An Introduction to Swift Inheritance Chapter 14. Working with Array and Dictionary Collections in Swift Chapter 15. The iOS 8 Application and Development Architecture Chapter 16. Creating an Interactive iOS 8 App Chapter 17. Understanding iOS 8 Views, Windows and the View Hierarchy Chapter 18. An Introduction to Auto Layout in iOS 8 Chapter 19. Working with iOS 8 Auto Layout Constraints in Interface Builder Chapter 20. An iOS 8 Auto Layout Example Chapter 21. Implementing iOS 8 Auto Layout Constraints in Code Chapter 22. Implementing Cross-Hierarchy Auto Layout Constraints in iOS 8 Chapter 23. Understanding the iOS 8 Auto Layout Visual Format Language Chapter 24. Using Size Classes to Design Universal iOS User Interfaces Chapter 25. Using Storyboards in Xcode 6 Chapter 26. Using Xcode 6 Storyboards to Create an iOS 8 Tab Bar Application Chapter 27. An Overview of iOS 8 Table Views and Xcode 6 Storyboards Chapter 28. Using Xcode 6 Storyboards to Build Dynamic TableViews with Prototype Table View Cells Chapter 29. Implementing iOS 8 TableView Navigation using Storyboards in Xcode 6 Chapter 30. An iOS 8 Split View Master-Detail Example Chapter 31. Implementing a Page based iOS 8 Application using UIPageViewController Chapter 32. An Example iOS 8 UIPageViewController Application Chapter 33. Working with Directories in Swift on iOS 8 Chapter 34. Working with Files in Swift on iOS 8 Chapter 35. iOS 8 Directory Handling and File I/O in Swift – A Worked Example Chapter 36. Preparing an iOS 8 App to use iCloud Storage Chapter 37. Managing Files using the iOS 8 UIDocument Class Chapter 38. Using iCloud Storage in an iOS 8 Application Chapter 39. Synchronizing iOS 8 Key-Value Data using iCloud Chapter 40. iOS 8 Data Persistence using Archiving Chapter 41. iOS 8 Database Implementation using SQLite Chapter 42. An Example SQLite based iOS 8 Application using Swift and FMDB Chapter 43. Working with iOS 8 Databases using Core Data Chapter 44. An iOS 8 Core Data Tutorial Chapter 45. An Introduction to CloudKit Data Storage on iOS 8 Chapter 46. An iOS 8 CloudKit Example Chapter 47. An iOS 8 CloudKit Subscription Example Chapter 48. An Overview of iOS 8 Multitouch, Taps and Gestures Chapter 49. An Example iOS 8 Touch, Multitouch and Tap Application Chapter 50. Detecting iOS 8 Touch Screen Gesture Motions Chapter 51. Identifying Gestures using iOS 8 Gesture Recognizers Chapter 52. An iOS 8 Gesture Recognition Tutorial Chapter 53. Implementing TouchID Authentication in iOS 8 Apps Chapter 54. An Overview of iOS 8 Collection View and Flow Layout Chapter 55. An iOS 8 Storyboard-based Collection View Tutorial Chapter 56. Subclassing and Extending the iOS 8 Collection View Flow Layout Chapter 57. Drawing iOS 8 2D Graphics with Core Graphics Chapter 58. Interface Builder Live Views and iOS 8 Embedded Frameworks Chapter 59. An iOS 8 Graphics Tutorial using Core Graphics and Core Image Chapter 60. Basic iOS 8 Animation using Core Animation Chapter 61. iOS 8 UIKit Dynamics – An Overview Chapter 62. An iOS 8 UIKit Dynamics Tutorial Chapter 63. An Introduction to iOS 8 Sprite Kit Programming Chapter 64. An iOS 8 Sprite Kit Level Editor Game Tutorial Chapter 65. An iOS 8 Sprite Kit Collision Handling Tutorial Chapter 66. An iOS 8 Sprite Kit Particle Emitter Tutorial Chapter 67. Integrating iAds into an iOS 8 App Chapter 68. iOS 8 Multitasking, Background Transfer Service and Fetching Chapter 69. Scheduling iOS 8 Local Notifications Chapter 70. An Overview of iOS 8 Application State Preservation and Restoration Chapter 71. An iOS 8 State Preservation and Restoration Tutorial Chapter 72. Integrating Maps into iOS 8 Applications using MKMapItem Chapter 73. An Example iOS 8 MKMapItem Application Chapter 74. Getting Location Information using the iOS 8 Core Location Framework Chapter 75. An Example iOS 8 Location Application Chapter 76. Working with Maps on iOS 8 with MapKit and the MKMapView Class Chapter 77. Working with MapKit Local Search in iOS 8 Chapter 78. Using MKDirections to get iOS 8 Map Directions and Routes Chapter 79. An Introduction to Extensions in iOS 8 Chapter 80. An iOS 8 Today Extension Widget Tutorial Chapter 81. Creating an iOS 8 Photo Editing Extension Chapter 82. Creating an iOS 8 Action Extension Chapter 83. Receiving Data from an iOS 8 Action Extension Chapter 84. Using iOS 8 Event Kit to Create Date and Location Based Reminders Chapter 85. Accessing the iOS 8 Camera and Photo Library Chapter 86. An Example iOS 8 Camera Application Chapter 87. iOS 8 Video Playback using AVPlayer and AVPlayerViewController Chapter 88. Playing Audio on iOS 8 using AVAudioPlayer Chapter 89. Recording Audio on iOS 8 with AVAudioRecorder Chapter 90. Integrating Twitter and Facebook into iOS 8 Applications Chapter 91. An iOS 8 Facebook Integration Tutorial using UIActivityViewController Chapter 92. iOS 8 Facebook and Twitter Integration using SLRequest Chapter 93. An iOS 8 Twitter Integration Tutorial using SLRequest Chapter 94. Making Store Purchases with the SKStoreProductViewController Class Chapter 95. Building In-App Purchasing into iOS 8 Applications Chapter 96. Preparing an iOS 8 Application for In-App Purchases Chapter 97. An iOS 8 In-App Purchase Tutorial Chapter 98. Configuring and Creating App Store Hosted Content for iOS 8 In-App Purchases Chapter 99. Preparing and Submitting an iOS 8 Application to the App Store

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值