├── LVDatabaseDemo.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ │ └── LVDatabaseDemo.xccheckout │ └── xcuserdata │ │ ├── liuchunlao.xcuserdatad │ │ └── UserInterfaceState.xcuserstate │ │ └── pboccs.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ ├── liuchunlao.xcuserdatad │ ├── xcdebugger │ │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ │ ├── LVDatabaseDemo.xcscheme │ │ └── xcschememanagement.plist │ └── pboccs.xcuserdatad │ └── xcschemes │ ├── LVDatabaseDemo.xcscheme │ └── xcschememanagement.plist ├── LVDatabaseDemo ├── AppDelegate.h ├── AppDelegate.m ├── Base.lproj │ ├── LaunchScreen.xib │ └── Main.storyboard ├── Classes │ ├── LVFmdbTool.h │ ├── LVFmdbTool.m │ └── fmdb │ │ ├── FMDB.h │ │ ├── FMDatabase.h │ │ ├── FMDatabase.m │ │ ├── FMDatabaseAdditions.h │ │ ├── FMDatabaseAdditions.m │ │ ├── FMDatabasePool.h │ │ ├── FMDatabasePool.m │ │ ├── FMDatabaseQueue.h │ │ ├── FMDatabaseQueue.m │ │ ├── FMResultSet.h │ │ └── FMResultSet.m ├── Images.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Info.plist ├── LVModel.h ├── LVModel.m ├── ViewController.h ├── ViewController.m └── main.m ├── LVDatabaseDemoTests ├── Info.plist └── LVDatabaseDemoTests.m └── README.md /LVDatabaseDemo.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 129CB0141AC3EFE800D87EA3 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 129CB0131AC3EFE800D87EA3 /* main.m */; }; 11 | 129CB0171AC3EFE800D87EA3 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 129CB0161AC3EFE800D87EA3 /* AppDelegate.m */; }; 12 | 129CB01A1AC3EFE800D87EA3 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 129CB0191AC3EFE800D87EA3 /* ViewController.m */; }; 13 | 129CB01D1AC3EFE800D87EA3 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 129CB01B1AC3EFE800D87EA3 /* Main.storyboard */; }; 14 | 129CB01F1AC3EFE800D87EA3 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 129CB01E1AC3EFE800D87EA3 /* Images.xcassets */; }; 15 | 129CB0221AC3EFE800D87EA3 /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 129CB0201AC3EFE800D87EA3 /* LaunchScreen.xib */; }; 16 | 129CB02E1AC3EFE800D87EA3 /* LVDatabaseDemoTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 129CB02D1AC3EFE800D87EA3 /* LVDatabaseDemoTests.m */; }; 17 | 12C068E41AC3F81600444FB0 /* libsqlite3.0.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 12C068E31AC3F81600444FB0 /* libsqlite3.0.dylib */; }; 18 | D905096F1AC4474200F33E25 /* LVModel.m in Sources */ = {isa = PBXBuildFile; fileRef = D905096E1AC4474200F33E25 /* LVModel.m */; }; 19 | D905097D1AC44E4700F33E25 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = D90509731AC44E4700F33E25 /* FMDatabase.m */; }; 20 | D905097E1AC44E4700F33E25 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = D90509751AC44E4700F33E25 /* FMDatabaseAdditions.m */; }; 21 | D905097F1AC44E4700F33E25 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = D90509771AC44E4700F33E25 /* FMDatabasePool.m */; }; 22 | D90509801AC44E4700F33E25 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = D90509791AC44E4700F33E25 /* FMDatabaseQueue.m */; }; 23 | D90509811AC44E4700F33E25 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = D905097C1AC44E4700F33E25 /* FMResultSet.m */; }; 24 | D90509841AC44E6A00F33E25 /* LVFmdbTool.m in Sources */ = {isa = PBXBuildFile; fileRef = D90509831AC44E6A00F33E25 /* LVFmdbTool.m */; }; 25 | /* End PBXBuildFile section */ 26 | 27 | /* Begin PBXContainerItemProxy section */ 28 | 129CB0281AC3EFE800D87EA3 /* PBXContainerItemProxy */ = { 29 | isa = PBXContainerItemProxy; 30 | containerPortal = 129CB0061AC3EFE800D87EA3 /* Project object */; 31 | proxyType = 1; 32 | remoteGlobalIDString = 129CB00D1AC3EFE800D87EA3; 33 | remoteInfo = LVDatabaseDemo; 34 | }; 35 | /* End PBXContainerItemProxy section */ 36 | 37 | /* Begin PBXFileReference section */ 38 | 129CB00E1AC3EFE800D87EA3 /* LVDatabaseDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LVDatabaseDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 39 | 129CB0121AC3EFE800D87EA3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 40 | 129CB0131AC3EFE800D87EA3 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 41 | 129CB0151AC3EFE800D87EA3 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 42 | 129CB0161AC3EFE800D87EA3 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 43 | 129CB0181AC3EFE800D87EA3 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 44 | 129CB0191AC3EFE800D87EA3 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 45 | 129CB01C1AC3EFE800D87EA3 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 46 | 129CB01E1AC3EFE800D87EA3 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; 47 | 129CB0211AC3EFE800D87EA3 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; }; 48 | 129CB0271AC3EFE800D87EA3 /* LVDatabaseDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = LVDatabaseDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 49 | 129CB02C1AC3EFE800D87EA3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 50 | 129CB02D1AC3EFE800D87EA3 /* LVDatabaseDemoTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = LVDatabaseDemoTests.m; sourceTree = ""; }; 51 | 12C068E31AC3F81600444FB0 /* libsqlite3.0.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.0.dylib; path = usr/lib/libsqlite3.0.dylib; sourceTree = SDKROOT; }; 52 | D905096D1AC4474200F33E25 /* LVModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LVModel.h; sourceTree = ""; }; 53 | D905096E1AC4474200F33E25 /* LVModel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = LVModel.m; sourceTree = ""; }; 54 | D90509721AC44E4700F33E25 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = ""; }; 55 | D90509731AC44E4700F33E25 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = ""; }; 56 | D90509741AC44E4700F33E25 /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = ""; }; 57 | D90509751AC44E4700F33E25 /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = ""; }; 58 | D90509761AC44E4700F33E25 /* FMDatabasePool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabasePool.h; sourceTree = ""; }; 59 | D90509771AC44E4700F33E25 /* FMDatabasePool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePool.m; sourceTree = ""; }; 60 | D90509781AC44E4700F33E25 /* FMDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseQueue.h; sourceTree = ""; }; 61 | D90509791AC44E4700F33E25 /* FMDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueue.m; sourceTree = ""; }; 62 | D905097A1AC44E4700F33E25 /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDB.h; sourceTree = ""; }; 63 | D905097B1AC44E4700F33E25 /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = ""; }; 64 | D905097C1AC44E4700F33E25 /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = ""; }; 65 | D90509821AC44E6A00F33E25 /* LVFmdbTool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LVFmdbTool.h; sourceTree = ""; }; 66 | D90509831AC44E6A00F33E25 /* LVFmdbTool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = LVFmdbTool.m; sourceTree = ""; }; 67 | /* End PBXFileReference section */ 68 | 69 | /* Begin PBXFrameworksBuildPhase section */ 70 | 129CB00B1AC3EFE800D87EA3 /* Frameworks */ = { 71 | isa = PBXFrameworksBuildPhase; 72 | buildActionMask = 2147483647; 73 | files = ( 74 | 12C068E41AC3F81600444FB0 /* libsqlite3.0.dylib in Frameworks */, 75 | ); 76 | runOnlyForDeploymentPostprocessing = 0; 77 | }; 78 | 129CB0241AC3EFE800D87EA3 /* Frameworks */ = { 79 | isa = PBXFrameworksBuildPhase; 80 | buildActionMask = 2147483647; 81 | files = ( 82 | ); 83 | runOnlyForDeploymentPostprocessing = 0; 84 | }; 85 | /* End PBXFrameworksBuildPhase section */ 86 | 87 | /* Begin PBXGroup section */ 88 | 129CB0051AC3EFE800D87EA3 = { 89 | isa = PBXGroup; 90 | children = ( 91 | 12C068E31AC3F81600444FB0 /* libsqlite3.0.dylib */, 92 | 129CB0101AC3EFE800D87EA3 /* LVDatabaseDemo */, 93 | 129CB02A1AC3EFE800D87EA3 /* LVDatabaseDemoTests */, 94 | 129CB00F1AC3EFE800D87EA3 /* Products */, 95 | ); 96 | sourceTree = ""; 97 | }; 98 | 129CB00F1AC3EFE800D87EA3 /* Products */ = { 99 | isa = PBXGroup; 100 | children = ( 101 | 129CB00E1AC3EFE800D87EA3 /* LVDatabaseDemo.app */, 102 | 129CB0271AC3EFE800D87EA3 /* LVDatabaseDemoTests.xctest */, 103 | ); 104 | name = Products; 105 | sourceTree = ""; 106 | }; 107 | 129CB0101AC3EFE800D87EA3 /* LVDatabaseDemo */ = { 108 | isa = PBXGroup; 109 | children = ( 110 | D90509701AC44E4700F33E25 /* Classes */, 111 | D905096D1AC4474200F33E25 /* LVModel.h */, 112 | D905096E1AC4474200F33E25 /* LVModel.m */, 113 | 129CB0151AC3EFE800D87EA3 /* AppDelegate.h */, 114 | 129CB0161AC3EFE800D87EA3 /* AppDelegate.m */, 115 | 129CB0181AC3EFE800D87EA3 /* ViewController.h */, 116 | 129CB0191AC3EFE800D87EA3 /* ViewController.m */, 117 | 129CB01B1AC3EFE800D87EA3 /* Main.storyboard */, 118 | 129CB01E1AC3EFE800D87EA3 /* Images.xcassets */, 119 | 129CB0201AC3EFE800D87EA3 /* LaunchScreen.xib */, 120 | 129CB0111AC3EFE800D87EA3 /* Supporting Files */, 121 | ); 122 | path = LVDatabaseDemo; 123 | sourceTree = ""; 124 | }; 125 | 129CB0111AC3EFE800D87EA3 /* Supporting Files */ = { 126 | isa = PBXGroup; 127 | children = ( 128 | 129CB0121AC3EFE800D87EA3 /* Info.plist */, 129 | 129CB0131AC3EFE800D87EA3 /* main.m */, 130 | ); 131 | name = "Supporting Files"; 132 | sourceTree = ""; 133 | }; 134 | 129CB02A1AC3EFE800D87EA3 /* LVDatabaseDemoTests */ = { 135 | isa = PBXGroup; 136 | children = ( 137 | 129CB02D1AC3EFE800D87EA3 /* LVDatabaseDemoTests.m */, 138 | 129CB02B1AC3EFE800D87EA3 /* Supporting Files */, 139 | ); 140 | path = LVDatabaseDemoTests; 141 | sourceTree = ""; 142 | }; 143 | 129CB02B1AC3EFE800D87EA3 /* Supporting Files */ = { 144 | isa = PBXGroup; 145 | children = ( 146 | 129CB02C1AC3EFE800D87EA3 /* Info.plist */, 147 | ); 148 | name = "Supporting Files"; 149 | sourceTree = ""; 150 | }; 151 | D90509701AC44E4700F33E25 /* Classes */ = { 152 | isa = PBXGroup; 153 | children = ( 154 | D90509711AC44E4700F33E25 /* fmdb */, 155 | D90509821AC44E6A00F33E25 /* LVFmdbTool.h */, 156 | D90509831AC44E6A00F33E25 /* LVFmdbTool.m */, 157 | ); 158 | path = Classes; 159 | sourceTree = ""; 160 | }; 161 | D90509711AC44E4700F33E25 /* fmdb */ = { 162 | isa = PBXGroup; 163 | children = ( 164 | D90509721AC44E4700F33E25 /* FMDatabase.h */, 165 | D90509731AC44E4700F33E25 /* FMDatabase.m */, 166 | D90509741AC44E4700F33E25 /* FMDatabaseAdditions.h */, 167 | D90509751AC44E4700F33E25 /* FMDatabaseAdditions.m */, 168 | D90509761AC44E4700F33E25 /* FMDatabasePool.h */, 169 | D90509771AC44E4700F33E25 /* FMDatabasePool.m */, 170 | D90509781AC44E4700F33E25 /* FMDatabaseQueue.h */, 171 | D90509791AC44E4700F33E25 /* FMDatabaseQueue.m */, 172 | D905097A1AC44E4700F33E25 /* FMDB.h */, 173 | D905097B1AC44E4700F33E25 /* FMResultSet.h */, 174 | D905097C1AC44E4700F33E25 /* FMResultSet.m */, 175 | ); 176 | path = fmdb; 177 | sourceTree = ""; 178 | }; 179 | /* End PBXGroup section */ 180 | 181 | /* Begin PBXNativeTarget section */ 182 | 129CB00D1AC3EFE800D87EA3 /* LVDatabaseDemo */ = { 183 | isa = PBXNativeTarget; 184 | buildConfigurationList = 129CB0311AC3EFE800D87EA3 /* Build configuration list for PBXNativeTarget "LVDatabaseDemo" */; 185 | buildPhases = ( 186 | 129CB00A1AC3EFE800D87EA3 /* Sources */, 187 | 129CB00B1AC3EFE800D87EA3 /* Frameworks */, 188 | 129CB00C1AC3EFE800D87EA3 /* Resources */, 189 | ); 190 | buildRules = ( 191 | ); 192 | dependencies = ( 193 | ); 194 | name = LVDatabaseDemo; 195 | productName = LVDatabaseDemo; 196 | productReference = 129CB00E1AC3EFE800D87EA3 /* LVDatabaseDemo.app */; 197 | productType = "com.apple.product-type.application"; 198 | }; 199 | 129CB0261AC3EFE800D87EA3 /* LVDatabaseDemoTests */ = { 200 | isa = PBXNativeTarget; 201 | buildConfigurationList = 129CB0341AC3EFE800D87EA3 /* Build configuration list for PBXNativeTarget "LVDatabaseDemoTests" */; 202 | buildPhases = ( 203 | 129CB0231AC3EFE800D87EA3 /* Sources */, 204 | 129CB0241AC3EFE800D87EA3 /* Frameworks */, 205 | 129CB0251AC3EFE800D87EA3 /* Resources */, 206 | ); 207 | buildRules = ( 208 | ); 209 | dependencies = ( 210 | 129CB0291AC3EFE800D87EA3 /* PBXTargetDependency */, 211 | ); 212 | name = LVDatabaseDemoTests; 213 | productName = LVDatabaseDemoTests; 214 | productReference = 129CB0271AC3EFE800D87EA3 /* LVDatabaseDemoTests.xctest */; 215 | productType = "com.apple.product-type.bundle.unit-test"; 216 | }; 217 | /* End PBXNativeTarget section */ 218 | 219 | /* Begin PBXProject section */ 220 | 129CB0061AC3EFE800D87EA3 /* Project object */ = { 221 | isa = PBXProject; 222 | attributes = { 223 | LastUpgradeCheck = 0620; 224 | ORGANIZATIONNAME = liuchunlao; 225 | TargetAttributes = { 226 | 129CB00D1AC3EFE800D87EA3 = { 227 | CreatedOnToolsVersion = 6.2; 228 | }; 229 | 129CB0261AC3EFE800D87EA3 = { 230 | CreatedOnToolsVersion = 6.2; 231 | TestTargetID = 129CB00D1AC3EFE800D87EA3; 232 | }; 233 | }; 234 | }; 235 | buildConfigurationList = 129CB0091AC3EFE800D87EA3 /* Build configuration list for PBXProject "LVDatabaseDemo" */; 236 | compatibilityVersion = "Xcode 3.2"; 237 | developmentRegion = English; 238 | hasScannedForEncodings = 0; 239 | knownRegions = ( 240 | en, 241 | Base, 242 | ); 243 | mainGroup = 129CB0051AC3EFE800D87EA3; 244 | productRefGroup = 129CB00F1AC3EFE800D87EA3 /* Products */; 245 | projectDirPath = ""; 246 | projectRoot = ""; 247 | targets = ( 248 | 129CB00D1AC3EFE800D87EA3 /* LVDatabaseDemo */, 249 | 129CB0261AC3EFE800D87EA3 /* LVDatabaseDemoTests */, 250 | ); 251 | }; 252 | /* End PBXProject section */ 253 | 254 | /* Begin PBXResourcesBuildPhase section */ 255 | 129CB00C1AC3EFE800D87EA3 /* Resources */ = { 256 | isa = PBXResourcesBuildPhase; 257 | buildActionMask = 2147483647; 258 | files = ( 259 | 129CB01D1AC3EFE800D87EA3 /* Main.storyboard in Resources */, 260 | 129CB0221AC3EFE800D87EA3 /* LaunchScreen.xib in Resources */, 261 | 129CB01F1AC3EFE800D87EA3 /* Images.xcassets in Resources */, 262 | ); 263 | runOnlyForDeploymentPostprocessing = 0; 264 | }; 265 | 129CB0251AC3EFE800D87EA3 /* Resources */ = { 266 | isa = PBXResourcesBuildPhase; 267 | buildActionMask = 2147483647; 268 | files = ( 269 | ); 270 | runOnlyForDeploymentPostprocessing = 0; 271 | }; 272 | /* End PBXResourcesBuildPhase section */ 273 | 274 | /* Begin PBXSourcesBuildPhase section */ 275 | 129CB00A1AC3EFE800D87EA3 /* Sources */ = { 276 | isa = PBXSourcesBuildPhase; 277 | buildActionMask = 2147483647; 278 | files = ( 279 | D905096F1AC4474200F33E25 /* LVModel.m in Sources */, 280 | D905097F1AC44E4700F33E25 /* FMDatabasePool.m in Sources */, 281 | D90509811AC44E4700F33E25 /* FMResultSet.m in Sources */, 282 | 129CB01A1AC3EFE800D87EA3 /* ViewController.m in Sources */, 283 | D90509801AC44E4700F33E25 /* FMDatabaseQueue.m in Sources */, 284 | D905097D1AC44E4700F33E25 /* FMDatabase.m in Sources */, 285 | D90509841AC44E6A00F33E25 /* LVFmdbTool.m in Sources */, 286 | 129CB0171AC3EFE800D87EA3 /* AppDelegate.m in Sources */, 287 | 129CB0141AC3EFE800D87EA3 /* main.m in Sources */, 288 | D905097E1AC44E4700F33E25 /* FMDatabaseAdditions.m in Sources */, 289 | ); 290 | runOnlyForDeploymentPostprocessing = 0; 291 | }; 292 | 129CB0231AC3EFE800D87EA3 /* Sources */ = { 293 | isa = PBXSourcesBuildPhase; 294 | buildActionMask = 2147483647; 295 | files = ( 296 | 129CB02E1AC3EFE800D87EA3 /* LVDatabaseDemoTests.m in Sources */, 297 | ); 298 | runOnlyForDeploymentPostprocessing = 0; 299 | }; 300 | /* End PBXSourcesBuildPhase section */ 301 | 302 | /* Begin PBXTargetDependency section */ 303 | 129CB0291AC3EFE800D87EA3 /* PBXTargetDependency */ = { 304 | isa = PBXTargetDependency; 305 | target = 129CB00D1AC3EFE800D87EA3 /* LVDatabaseDemo */; 306 | targetProxy = 129CB0281AC3EFE800D87EA3 /* PBXContainerItemProxy */; 307 | }; 308 | /* End PBXTargetDependency section */ 309 | 310 | /* Begin PBXVariantGroup section */ 311 | 129CB01B1AC3EFE800D87EA3 /* Main.storyboard */ = { 312 | isa = PBXVariantGroup; 313 | children = ( 314 | 129CB01C1AC3EFE800D87EA3 /* Base */, 315 | ); 316 | name = Main.storyboard; 317 | sourceTree = ""; 318 | }; 319 | 129CB0201AC3EFE800D87EA3 /* LaunchScreen.xib */ = { 320 | isa = PBXVariantGroup; 321 | children = ( 322 | 129CB0211AC3EFE800D87EA3 /* Base */, 323 | ); 324 | name = LaunchScreen.xib; 325 | sourceTree = ""; 326 | }; 327 | /* End PBXVariantGroup section */ 328 | 329 | /* Begin XCBuildConfiguration section */ 330 | 129CB02F1AC3EFE800D87EA3 /* Debug */ = { 331 | isa = XCBuildConfiguration; 332 | buildSettings = { 333 | ALWAYS_SEARCH_USER_PATHS = NO; 334 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 335 | CLANG_CXX_LIBRARY = "libc++"; 336 | CLANG_ENABLE_MODULES = YES; 337 | CLANG_ENABLE_OBJC_ARC = YES; 338 | CLANG_WARN_BOOL_CONVERSION = YES; 339 | CLANG_WARN_CONSTANT_CONVERSION = YES; 340 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 341 | CLANG_WARN_EMPTY_BODY = YES; 342 | CLANG_WARN_ENUM_CONVERSION = YES; 343 | CLANG_WARN_INT_CONVERSION = YES; 344 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 345 | CLANG_WARN_UNREACHABLE_CODE = YES; 346 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 347 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 348 | COPY_PHASE_STRIP = NO; 349 | ENABLE_STRICT_OBJC_MSGSEND = YES; 350 | GCC_C_LANGUAGE_STANDARD = gnu99; 351 | GCC_DYNAMIC_NO_PIC = NO; 352 | GCC_OPTIMIZATION_LEVEL = 0; 353 | GCC_PREPROCESSOR_DEFINITIONS = ( 354 | "DEBUG=1", 355 | "$(inherited)", 356 | ); 357 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 358 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 359 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 360 | GCC_WARN_UNDECLARED_SELECTOR = YES; 361 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 362 | GCC_WARN_UNUSED_FUNCTION = YES; 363 | GCC_WARN_UNUSED_VARIABLE = YES; 364 | IPHONEOS_DEPLOYMENT_TARGET = 8.2; 365 | MTL_ENABLE_DEBUG_INFO = YES; 366 | ONLY_ACTIVE_ARCH = YES; 367 | SDKROOT = iphoneos; 368 | TARGETED_DEVICE_FAMILY = "1,2"; 369 | }; 370 | name = Debug; 371 | }; 372 | 129CB0301AC3EFE800D87EA3 /* Release */ = { 373 | isa = XCBuildConfiguration; 374 | buildSettings = { 375 | ALWAYS_SEARCH_USER_PATHS = NO; 376 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 377 | CLANG_CXX_LIBRARY = "libc++"; 378 | CLANG_ENABLE_MODULES = YES; 379 | CLANG_ENABLE_OBJC_ARC = YES; 380 | CLANG_WARN_BOOL_CONVERSION = YES; 381 | CLANG_WARN_CONSTANT_CONVERSION = YES; 382 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 383 | CLANG_WARN_EMPTY_BODY = YES; 384 | CLANG_WARN_ENUM_CONVERSION = YES; 385 | CLANG_WARN_INT_CONVERSION = YES; 386 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 387 | CLANG_WARN_UNREACHABLE_CODE = YES; 388 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 389 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 390 | COPY_PHASE_STRIP = NO; 391 | ENABLE_NS_ASSERTIONS = NO; 392 | ENABLE_STRICT_OBJC_MSGSEND = YES; 393 | GCC_C_LANGUAGE_STANDARD = gnu99; 394 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 395 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 396 | GCC_WARN_UNDECLARED_SELECTOR = YES; 397 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 398 | GCC_WARN_UNUSED_FUNCTION = YES; 399 | GCC_WARN_UNUSED_VARIABLE = YES; 400 | IPHONEOS_DEPLOYMENT_TARGET = 8.2; 401 | MTL_ENABLE_DEBUG_INFO = NO; 402 | SDKROOT = iphoneos; 403 | TARGETED_DEVICE_FAMILY = "1,2"; 404 | VALIDATE_PRODUCT = YES; 405 | }; 406 | name = Release; 407 | }; 408 | 129CB0321AC3EFE800D87EA3 /* Debug */ = { 409 | isa = XCBuildConfiguration; 410 | buildSettings = { 411 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 412 | INFOPLIST_FILE = LVDatabaseDemo/Info.plist; 413 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 414 | PRODUCT_NAME = "$(TARGET_NAME)"; 415 | }; 416 | name = Debug; 417 | }; 418 | 129CB0331AC3EFE800D87EA3 /* Release */ = { 419 | isa = XCBuildConfiguration; 420 | buildSettings = { 421 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 422 | INFOPLIST_FILE = LVDatabaseDemo/Info.plist; 423 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 424 | PRODUCT_NAME = "$(TARGET_NAME)"; 425 | }; 426 | name = Release; 427 | }; 428 | 129CB0351AC3EFE800D87EA3 /* Debug */ = { 429 | isa = XCBuildConfiguration; 430 | buildSettings = { 431 | BUNDLE_LOADER = "$(TEST_HOST)"; 432 | FRAMEWORK_SEARCH_PATHS = ( 433 | "$(SDKROOT)/Developer/Library/Frameworks", 434 | "$(inherited)", 435 | ); 436 | GCC_PREPROCESSOR_DEFINITIONS = ( 437 | "DEBUG=1", 438 | "$(inherited)", 439 | ); 440 | INFOPLIST_FILE = LVDatabaseDemoTests/Info.plist; 441 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 442 | PRODUCT_NAME = "$(TARGET_NAME)"; 443 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/LVDatabaseDemo.app/LVDatabaseDemo"; 444 | }; 445 | name = Debug; 446 | }; 447 | 129CB0361AC3EFE800D87EA3 /* Release */ = { 448 | isa = XCBuildConfiguration; 449 | buildSettings = { 450 | BUNDLE_LOADER = "$(TEST_HOST)"; 451 | FRAMEWORK_SEARCH_PATHS = ( 452 | "$(SDKROOT)/Developer/Library/Frameworks", 453 | "$(inherited)", 454 | ); 455 | INFOPLIST_FILE = LVDatabaseDemoTests/Info.plist; 456 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 457 | PRODUCT_NAME = "$(TARGET_NAME)"; 458 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/LVDatabaseDemo.app/LVDatabaseDemo"; 459 | }; 460 | name = Release; 461 | }; 462 | /* End XCBuildConfiguration section */ 463 | 464 | /* Begin XCConfigurationList section */ 465 | 129CB0091AC3EFE800D87EA3 /* Build configuration list for PBXProject "LVDatabaseDemo" */ = { 466 | isa = XCConfigurationList; 467 | buildConfigurations = ( 468 | 129CB02F1AC3EFE800D87EA3 /* Debug */, 469 | 129CB0301AC3EFE800D87EA3 /* Release */, 470 | ); 471 | defaultConfigurationIsVisible = 0; 472 | defaultConfigurationName = Release; 473 | }; 474 | 129CB0311AC3EFE800D87EA3 /* Build configuration list for PBXNativeTarget "LVDatabaseDemo" */ = { 475 | isa = XCConfigurationList; 476 | buildConfigurations = ( 477 | 129CB0321AC3EFE800D87EA3 /* Debug */, 478 | 129CB0331AC3EFE800D87EA3 /* Release */, 479 | ); 480 | defaultConfigurationIsVisible = 0; 481 | defaultConfigurationName = Release; 482 | }; 483 | 129CB0341AC3EFE800D87EA3 /* Build configuration list for PBXNativeTarget "LVDatabaseDemoTests" */ = { 484 | isa = XCConfigurationList; 485 | buildConfigurations = ( 486 | 129CB0351AC3EFE800D87EA3 /* Debug */, 487 | 129CB0361AC3EFE800D87EA3 /* Release */, 488 | ); 489 | defaultConfigurationIsVisible = 0; 490 | defaultConfigurationName = Release; 491 | }; 492 | /* End XCConfigurationList section */ 493 | }; 494 | rootObject = 129CB0061AC3EFE800D87EA3 /* Project object */; 495 | } 496 | -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/project.xcworkspace/xcshareddata/LVDatabaseDemo.xccheckout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDESourceControlProjectFavoriteDictionaryKey 6 | 7 | IDESourceControlProjectIdentifier 8 | BBBA45D7-DB06-4177-9567-3F045964B450 9 | IDESourceControlProjectName 10 | LVDatabaseDemo 11 | IDESourceControlProjectOriginsDictionary 12 | 13 | 40A10516B75AED7AB1AF10223CA7936C24FA4B48 14 | https://github.com/liuchunlao/LVDatabaseDemo.git 15 | 16 | IDESourceControlProjectPath 17 | LVDatabaseDemo.xcodeproj 18 | IDESourceControlProjectRelativeInstallPathDictionary 19 | 20 | 40A10516B75AED7AB1AF10223CA7936C24FA4B48 21 | ../.. 22 | 23 | IDESourceControlProjectURL 24 | https://github.com/liuchunlao/LVDatabaseDemo.git 25 | IDESourceControlProjectVersion 26 | 111 27 | IDESourceControlProjectWCCIdentifier 28 | 40A10516B75AED7AB1AF10223CA7936C24FA4B48 29 | IDESourceControlProjectWCConfigurations 30 | 31 | 32 | IDESourceControlRepositoryExtensionIdentifierKey 33 | public.vcs.git 34 | IDESourceControlWCCIdentifierKey 35 | 40A10516B75AED7AB1AF10223CA7936C24FA4B48 36 | IDESourceControlWCCName 37 | LVDatabaseDemo 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/project.xcworkspace/xcuserdata/liuchunlao.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuchunlao/LVDatabaseDemo/7349fcd9d799980af5bb0e54b50a9ce593d49581/LVDatabaseDemo.xcodeproj/project.xcworkspace/xcuserdata/liuchunlao.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/project.xcworkspace/xcuserdata/pboccs.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuchunlao/LVDatabaseDemo/7349fcd9d799980af5bb0e54b50a9ce593d49581/LVDatabaseDemo.xcodeproj/project.xcworkspace/xcuserdata/pboccs.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/xcuserdata/liuchunlao.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/xcuserdata/liuchunlao.xcuserdatad/xcschemes/LVDatabaseDemo.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 65 | 66 | 75 | 77 | 83 | 84 | 85 | 86 | 87 | 88 | 94 | 96 | 102 | 103 | 104 | 105 | 107 | 108 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/xcuserdata/liuchunlao.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | LVDatabaseDemo.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 129CB00D1AC3EFE800D87EA3 16 | 17 | primary 18 | 19 | 20 | 129CB0261AC3EFE800D87EA3 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/xcuserdata/pboccs.xcuserdatad/xcschemes/LVDatabaseDemo.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 65 | 66 | 75 | 77 | 83 | 84 | 85 | 86 | 87 | 88 | 94 | 96 | 102 | 103 | 104 | 105 | 107 | 108 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /LVDatabaseDemo.xcodeproj/xcuserdata/pboccs.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | LVDatabaseDemo.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 129CB00D1AC3EFE800D87EA3 16 | 17 | primary 18 | 19 | 20 | 129CB0261AC3EFE800D87EA3 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /LVDatabaseDemo/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // LVDatabaseDemo 4 | // 5 | // Created by PBOC CS on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /LVDatabaseDemo/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // LVDatabaseDemo 4 | // 5 | // Created by PBOC CS on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | - (void)applicationWillResignActive:(UIApplication *)application { 24 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 26 | } 27 | 28 | - (void)applicationDidEnterBackground:(UIApplication *)application { 29 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 31 | } 32 | 33 | - (void)applicationWillEnterForeground:(UIApplication *)application { 34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 35 | } 36 | 37 | - (void)applicationDidBecomeActive:(UIApplication *)application { 38 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 39 | } 40 | 41 | - (void)applicationWillTerminate:(UIApplication *)application { 42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 43 | } 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 20 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 50 | 66 | 78 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/LVFmdbTool.h: -------------------------------------------------------------------------------- 1 | // 2 | // LVFmdbTool.h 3 | // LVDatabaseDemo 4 | // 5 | // Created by 刘春牢 on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "FMDB.h" 11 | 12 | @class LVModal; 13 | @interface LVFmdbTool : NSObject 14 | 15 | // 插入模型数据 16 | + (BOOL)insertModel:(LVModal *)model; 17 | 18 | /** 查询数据,如果 传空 默认会查询表中所有数据 */ 19 | + (NSArray *)queryData:(NSString *)querySql; 20 | 21 | /** 删除数据,如果 传空 默认会删除表中所有数据 */ 22 | + (BOOL)deleteData:(NSString *)deleteSql; 23 | 24 | /** 修改数据 */ 25 | + (BOOL)modifyData:(NSString *)modifySql; 26 | 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/LVFmdbTool.m: -------------------------------------------------------------------------------- 1 | // 2 | // LVFmdbTool.m 3 | // LVDatabaseDemo 4 | // 5 | // Created by 刘春牢 on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import "LVFmdbTool.h" 10 | #import "LVModel.h" 11 | 12 | #define LVSQLITE_NAME @"modals.sqlite" 13 | 14 | @implementation LVFmdbTool 15 | 16 | 17 | static FMDatabase *_fmdb; 18 | 19 | + (void)initialize { 20 | // 执行打开数据库和创建表操作 21 | NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:LVSQLITE_NAME]; 22 | _fmdb = [FMDatabase databaseWithPath:filePath]; 23 | 24 | [_fmdb open]; 25 | 26 | #warning 必须先打开数据库才能创建表。。。否则提示数据库没有打开 27 | [_fmdb executeUpdate:@"CREATE TABLE IF NOT EXISTS t_modals(id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER NOT NULL, ID_No INTEGER NOT NULL);"]; 28 | } 29 | 30 | + (BOOL)insertModel:(LVModel *)model { 31 | NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO t_modals(name, age, ID_No) VALUES ('%@', '%zd', '%zd');", model.name, model.age, model.ID_No]; 32 | return [_fmdb executeUpdate:insertSql]; 33 | } 34 | 35 | + (NSArray *)queryData:(NSString *)querySql { 36 | 37 | if (querySql == nil) { 38 | querySql = @"SELECT * FROM t_modals;"; 39 | } 40 | 41 | NSMutableArray *arrM = [NSMutableArray array]; 42 | FMResultSet *set = [_fmdb executeQuery:querySql]; 43 | 44 | while ([set next]) { 45 | 46 | NSString *name = [set stringForColumn:@"name"]; 47 | NSString *age = [set stringForColumn:@"age"]; 48 | NSString *ID_No = [set stringForColumn:@"ID_No"]; 49 | 50 | LVModel *modal = [LVModel modalWith:name age:age.intValue no:ID_No.intValue]; 51 | [arrM addObject:modal]; 52 | } 53 | return arrM; 54 | } 55 | 56 | + (BOOL)deleteData:(NSString *)deleteSql { 57 | 58 | if (deleteSql == nil) { 59 | deleteSql = @"DELETE FROM t_modals"; 60 | } 61 | 62 | return [_fmdb executeUpdate:deleteSql]; 63 | 64 | } 65 | 66 | + (BOOL)modifyData:(NSString *)modifySql { 67 | 68 | if (modifySql == nil) { 69 | modifySql = @"UPDATE t_modals SET ID_No = '789789' WHERE name = 'lisi'"; 70 | } 71 | return [_fmdb executeUpdate:modifySql]; 72 | } 73 | 74 | 75 | 76 | @end 77 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDB.h: -------------------------------------------------------------------------------- 1 | #import "FMDatabase.h" 2 | #import "FMResultSet.h" 3 | #import "FMDatabaseAdditions.h" 4 | #import "FMDatabaseQueue.h" 5 | #import "FMDatabasePool.h" 6 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDatabase.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "sqlite3.h" 3 | #import "FMResultSet.h" 4 | #import "FMDatabasePool.h" 5 | 6 | 7 | #if ! __has_feature(objc_arc) 8 | #define FMDBAutorelease(__v) ([__v autorelease]); 9 | #define FMDBReturnAutoreleased FMDBAutorelease 10 | 11 | #define FMDBRetain(__v) ([__v retain]); 12 | #define FMDBReturnRetained FMDBRetain 13 | 14 | #define FMDBRelease(__v) ([__v release]); 15 | 16 | #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); 17 | #else 18 | // -fobjc-arc 19 | #define FMDBAutorelease(__v) 20 | #define FMDBReturnAutoreleased(__v) (__v) 21 | 22 | #define FMDBRetain(__v) 23 | #define FMDBReturnRetained(__v) (__v) 24 | 25 | #define FMDBRelease(__v) 26 | 27 | // If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects 28 | // and will participate in ARC. 29 | // See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. 30 | #if OS_OBJECT_USE_OBJC 31 | #define FMDBDispatchQueueRelease(__v) 32 | #else 33 | #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); 34 | #endif 35 | #endif 36 | 37 | #if !__has_feature(objc_instancetype) 38 | #define instancetype id 39 | #endif 40 | 41 | 42 | typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); 43 | 44 | 45 | /** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper. 46 | 47 | ### Usage 48 | The three main classes in FMDB are: 49 | 50 | - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. 51 | - `` - Represents the results of executing a query on an `FMDatabase`. 52 | - `` - If you want to perform queries and updates on multiple threads, you'll want to use this class. 53 | 54 | ### See also 55 | 56 | - `` - A pool of `FMDatabase` objects. 57 | - `` - A wrapper for `sqlite_stmt`. 58 | 59 | ### External links 60 | 61 | - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation 62 | - [SQLite web site](http://sqlite.org/) 63 | - [FMDB mailing list](http://groups.google.com/group/fmdb) 64 | - [SQLite FAQ](http://www.sqlite.org/faq.html) 65 | 66 | @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use ``. 67 | 68 | */ 69 | 70 | #pragma clang diagnostic push 71 | #pragma clang diagnostic ignored "-Wobjc-interface-ivars" 72 | 73 | 74 | @interface FMDatabase : NSObject { 75 | 76 | sqlite3* _db; 77 | NSString* _databasePath; 78 | BOOL _logsErrors; 79 | BOOL _crashOnErrors; 80 | BOOL _traceExecution; 81 | BOOL _checkedOut; 82 | BOOL _shouldCacheStatements; 83 | BOOL _isExecutingStatement; 84 | BOOL _inTransaction; 85 | NSTimeInterval _maxBusyRetryTimeInterval; 86 | NSTimeInterval _startBusyRetryTime; 87 | 88 | NSMutableDictionary *_cachedStatements; 89 | NSMutableSet *_openResultSets; 90 | NSMutableSet *_openFunctions; 91 | 92 | NSDateFormatter *_dateFormat; 93 | } 94 | 95 | ///----------------- 96 | /// @name Properties 97 | ///----------------- 98 | 99 | /** Whether should trace execution */ 100 | 101 | @property (atomic, assign) BOOL traceExecution; 102 | 103 | /** Whether checked out or not */ 104 | 105 | @property (atomic, assign) BOOL checkedOut; 106 | 107 | /** Crash on errors */ 108 | 109 | @property (atomic, assign) BOOL crashOnErrors; 110 | 111 | /** Logs errors */ 112 | 113 | @property (atomic, assign) BOOL logsErrors; 114 | 115 | /** Dictionary of cached statements */ 116 | 117 | @property (atomic, retain) NSMutableDictionary *cachedStatements; 118 | 119 | ///--------------------- 120 | /// @name Initialization 121 | ///--------------------- 122 | 123 | /** Create a `FMDatabase` object. 124 | 125 | An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 126 | 127 | 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 128 | 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 129 | 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. 130 | 131 | For example, to create/open a database in your Mac OS X `tmp` folder: 132 | 133 | FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; 134 | 135 | Or, in iOS, you might open a database in the app's `Documents` directory: 136 | 137 | NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 138 | NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; 139 | FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; 140 | 141 | (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) 142 | 143 | @param inPath Path of database file 144 | 145 | @return `FMDatabase` object if successful; `nil` if failure. 146 | 147 | */ 148 | 149 | + (instancetype)databaseWithPath:(NSString*)inPath; 150 | 151 | /** Initialize a `FMDatabase` object. 152 | 153 | An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 154 | 155 | 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 156 | 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 157 | 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. 158 | 159 | For example, to create/open a database in your Mac OS X `tmp` folder: 160 | 161 | FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; 162 | 163 | Or, in iOS, you might open a database in the app's `Documents` directory: 164 | 165 | NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 166 | NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; 167 | FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; 168 | 169 | (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) 170 | 171 | @param inPath Path of database file 172 | 173 | @return `FMDatabase` object if successful; `nil` if failure. 174 | 175 | */ 176 | 177 | - (instancetype)initWithPath:(NSString*)inPath; 178 | 179 | 180 | ///----------------------------------- 181 | /// @name Opening and closing database 182 | ///----------------------------------- 183 | 184 | /** Opening a new database connection 185 | 186 | The database is opened for reading and writing, and is created if it does not already exist. 187 | 188 | @return `YES` if successful, `NO` on error. 189 | 190 | @see [sqlite3_open()](http://sqlite.org/c3ref/open.html) 191 | @see openWithFlags: 192 | @see close 193 | */ 194 | 195 | - (BOOL)open; 196 | 197 | /** Opening a new database connection with flags 198 | 199 | @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: 200 | 201 | `SQLITE_OPEN_READONLY` 202 | 203 | The database is opened in read-only mode. If the database does not already exist, an error is returned. 204 | 205 | `SQLITE_OPEN_READWRITE` 206 | 207 | The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. 208 | 209 | `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` 210 | 211 | The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. 212 | 213 | @return `YES` if successful, `NO` on error. 214 | 215 | @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) 216 | @see open 217 | @see close 218 | */ 219 | 220 | #if SQLITE_VERSION_NUMBER >= 3005000 221 | - (BOOL)openWithFlags:(int)flags; 222 | #endif 223 | 224 | /** Closing a database connection 225 | 226 | @return `YES` if success, `NO` on error. 227 | 228 | @see [sqlite3_close()](http://sqlite.org/c3ref/close.html) 229 | @see open 230 | @see openWithFlags: 231 | */ 232 | 233 | - (BOOL)close; 234 | 235 | /** Test to see if we have a good connection to the database. 236 | 237 | This will confirm whether: 238 | 239 | - is database open 240 | - if open, it will try a simple SELECT statement and confirm that it succeeds. 241 | 242 | @return `YES` if everything succeeds, `NO` on failure. 243 | */ 244 | 245 | - (BOOL)goodConnection; 246 | 247 | 248 | ///---------------------- 249 | /// @name Perform updates 250 | ///---------------------- 251 | 252 | /** Execute single update statement 253 | 254 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. 255 | 256 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 257 | 258 | @param sql The SQL to be performed, with optional `?` placeholders. 259 | 260 | @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. 261 | 262 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 263 | 264 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 265 | 266 | @see lastError 267 | @see lastErrorCode 268 | @see lastErrorMessage 269 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 270 | */ 271 | 272 | - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...; 273 | 274 | /** Execute single update statement 275 | 276 | @see executeUpdate:withErrorAndBindings: 277 | 278 | @warning **Deprecated**: Please use `` instead. 279 | */ 280 | 281 | - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated)); 282 | 283 | /** Execute single update statement 284 | 285 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. 286 | 287 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 288 | 289 | @param sql The SQL to be performed, with optional `?` placeholders. 290 | 291 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 292 | 293 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 294 | 295 | @see lastError 296 | @see lastErrorCode 297 | @see lastErrorMessage 298 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 299 | 300 | @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. 301 | 302 | @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as ``. 303 | */ 304 | 305 | - (BOOL)executeUpdate:(NSString*)sql, ...; 306 | 307 | /** Execute single update statement 308 | 309 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. 310 | 311 | @param format The SQL to be performed, with `printf`-style escape sequences. 312 | 313 | @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. 314 | 315 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 316 | 317 | @see executeUpdate: 318 | @see lastError 319 | @see lastErrorCode 320 | @see lastErrorMessage 321 | 322 | @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command 323 | 324 | [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; 325 | 326 | is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` 327 | 328 | [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; 329 | 330 | There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`. 331 | */ 332 | 333 | - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); 334 | 335 | /** Execute single update statement 336 | 337 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. 338 | 339 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 340 | 341 | @param sql The SQL to be performed, with optional `?` placeholders. 342 | 343 | @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. 344 | 345 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 346 | 347 | @see lastError 348 | @see lastErrorCode 349 | @see lastErrorMessage 350 | */ 351 | 352 | - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; 353 | 354 | /** Execute single update statement 355 | 356 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. 357 | 358 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 359 | 360 | @param sql The SQL to be performed, with optional `?` placeholders. 361 | 362 | @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. 363 | 364 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 365 | 366 | @see lastError 367 | @see lastErrorCode 368 | @see lastErrorMessage 369 | */ 370 | 371 | - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; 372 | 373 | 374 | /** Execute single update statement 375 | 376 | This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. 377 | 378 | The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. 379 | 380 | @param sql The SQL to be performed, with optional `?` placeholders. 381 | 382 | @param args A `va_list` of arguments. 383 | 384 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 385 | 386 | @see lastError 387 | @see lastErrorCode 388 | @see lastErrorMessage 389 | */ 390 | 391 | - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; 392 | 393 | /** Execute multiple SQL statements 394 | 395 | This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 396 | 397 | @param sql The SQL to be performed 398 | 399 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 400 | 401 | @see executeStatements:withResultBlock: 402 | @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) 403 | 404 | */ 405 | 406 | - (BOOL)executeStatements:(NSString *)sql; 407 | 408 | /** Execute multiple SQL statements with callback handler 409 | 410 | This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. 411 | 412 | @param sql The SQL to be performed. 413 | @param block A block that will be called for any result sets returned by any SQL statements. 414 | Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), 415 | non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. 416 | This may be `nil` if you don't care to receive any results. 417 | 418 | @return `YES` upon success; `NO` upon failure. If failed, you can call ``, 419 | ``, or `` for diagnostic information regarding the failure. 420 | 421 | @see executeStatements: 422 | @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) 423 | 424 | */ 425 | 426 | - (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block; 427 | 428 | /** Last insert rowid 429 | 430 | Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid. 431 | 432 | This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. 433 | 434 | @return The rowid of the last inserted row. 435 | 436 | @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html) 437 | 438 | */ 439 | 440 | - (sqlite_int64)lastInsertRowId; 441 | 442 | /** The number of rows changed by prior SQL statement. 443 | 444 | This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. 445 | 446 | @return The number of rows changed by prior SQL statement. 447 | 448 | @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html) 449 | 450 | */ 451 | 452 | - (int)changes; 453 | 454 | 455 | ///------------------------- 456 | /// @name Retrieving results 457 | ///------------------------- 458 | 459 | /** Execute select statement 460 | 461 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 462 | 463 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 464 | 465 | This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. 466 | 467 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 468 | 469 | @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). 470 | 471 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 472 | 473 | @see FMResultSet 474 | @see [`FMResultSet next`](<[FMResultSet next]>) 475 | @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) 476 | 477 | @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as ``. 478 | */ 479 | 480 | - (FMResultSet *)executeQuery:(NSString*)sql, ...; 481 | 482 | /** Execute select statement 483 | 484 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 485 | 486 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 487 | 488 | @param format The SQL to be performed, with `printf`-style escape sequences. 489 | 490 | @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. 491 | 492 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 493 | 494 | @see executeQuery: 495 | @see FMResultSet 496 | @see [`FMResultSet next`](<[FMResultSet next]>) 497 | 498 | @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command 499 | 500 | [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; 501 | 502 | is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` 503 | 504 | [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; 505 | 506 | There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`. 507 | 508 | */ 509 | 510 | - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); 511 | 512 | /** Execute select statement 513 | 514 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 515 | 516 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 517 | 518 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 519 | 520 | @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. 521 | 522 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 523 | 524 | @see FMResultSet 525 | @see [`FMResultSet next`](<[FMResultSet next]>) 526 | */ 527 | 528 | - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; 529 | 530 | /** Execute select statement 531 | 532 | Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. 533 | 534 | In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. 535 | 536 | @param sql The SELECT statement to be performed, with optional `?` placeholders. 537 | 538 | @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. 539 | 540 | @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 541 | 542 | @see FMResultSet 543 | @see [`FMResultSet next`](<[FMResultSet next]>) 544 | */ 545 | 546 | - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments; 547 | 548 | 549 | // Documentation forthcoming. 550 | - (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args; 551 | 552 | ///------------------- 553 | /// @name Transactions 554 | ///------------------- 555 | 556 | /** Begin a transaction 557 | 558 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 559 | 560 | @see commit 561 | @see rollback 562 | @see beginDeferredTransaction 563 | @see inTransaction 564 | */ 565 | 566 | - (BOOL)beginTransaction; 567 | 568 | /** Begin a deferred transaction 569 | 570 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 571 | 572 | @see commit 573 | @see rollback 574 | @see beginTransaction 575 | @see inTransaction 576 | */ 577 | 578 | - (BOOL)beginDeferredTransaction; 579 | 580 | /** Commit a transaction 581 | 582 | Commit a transaction that was initiated with either `` or with ``. 583 | 584 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 585 | 586 | @see beginTransaction 587 | @see beginDeferredTransaction 588 | @see rollback 589 | @see inTransaction 590 | */ 591 | 592 | - (BOOL)commit; 593 | 594 | /** Rollback a transaction 595 | 596 | Rollback a transaction that was initiated with either `` or with ``. 597 | 598 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 599 | 600 | @see beginTransaction 601 | @see beginDeferredTransaction 602 | @see commit 603 | @see inTransaction 604 | */ 605 | 606 | - (BOOL)rollback; 607 | 608 | /** Identify whether currently in a transaction or not 609 | 610 | @return `YES` if currently within transaction; `NO` if not. 611 | 612 | @see beginTransaction 613 | @see beginDeferredTransaction 614 | @see commit 615 | @see rollback 616 | */ 617 | 618 | - (BOOL)inTransaction; 619 | 620 | 621 | ///---------------------------------------- 622 | /// @name Cached statements and result sets 623 | ///---------------------------------------- 624 | 625 | /** Clear cached statements */ 626 | 627 | - (void)clearCachedStatements; 628 | 629 | /** Close all open result sets */ 630 | 631 | - (void)closeOpenResultSets; 632 | 633 | /** Whether database has any open result sets 634 | 635 | @return `YES` if there are open result sets; `NO` if not. 636 | */ 637 | 638 | - (BOOL)hasOpenResultSets; 639 | 640 | /** Return whether should cache statements or not 641 | 642 | @return `YES` if should cache statements; `NO` if not. 643 | */ 644 | 645 | - (BOOL)shouldCacheStatements; 646 | 647 | /** Set whether should cache statements or not 648 | 649 | @param value `YES` if should cache statements; `NO` if not. 650 | */ 651 | 652 | - (void)setShouldCacheStatements:(BOOL)value; 653 | 654 | 655 | ///------------------------- 656 | /// @name Encryption methods 657 | ///------------------------- 658 | 659 | /** Set encryption key. 660 | 661 | @param key The key to be used. 662 | 663 | @return `YES` if success, `NO` on error. 664 | 665 | @see http://www.sqlite-encrypt.com/develop-guide.htm 666 | 667 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 668 | */ 669 | 670 | - (BOOL)setKey:(NSString*)key; 671 | 672 | /** Reset encryption key 673 | 674 | @param key The key to be used. 675 | 676 | @return `YES` if success, `NO` on error. 677 | 678 | @see http://www.sqlite-encrypt.com/develop-guide.htm 679 | 680 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 681 | */ 682 | 683 | - (BOOL)rekey:(NSString*)key; 684 | 685 | /** Set encryption key using `keyData`. 686 | 687 | @param keyData The `NSData` to be used. 688 | 689 | @return `YES` if success, `NO` on error. 690 | 691 | @see http://www.sqlite-encrypt.com/develop-guide.htm 692 | 693 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 694 | */ 695 | 696 | - (BOOL)setKeyWithData:(NSData *)keyData; 697 | 698 | /** Reset encryption key using `keyData`. 699 | 700 | @param keyData The `NSData` to be used. 701 | 702 | @return `YES` if success, `NO` on error. 703 | 704 | @see http://www.sqlite-encrypt.com/develop-guide.htm 705 | 706 | @warning You need to have purchased the sqlite encryption extensions for this method to work. 707 | */ 708 | 709 | - (BOOL)rekeyWithData:(NSData *)keyData; 710 | 711 | 712 | ///------------------------------ 713 | /// @name General inquiry methods 714 | ///------------------------------ 715 | 716 | /** The path of the database file 717 | 718 | @return path of database. 719 | 720 | */ 721 | 722 | - (NSString *)databasePath; 723 | 724 | /** The underlying SQLite handle 725 | 726 | @return The `sqlite3` pointer. 727 | 728 | */ 729 | 730 | - (sqlite3*)sqliteHandle; 731 | 732 | 733 | ///----------------------------- 734 | /// @name Retrieving error codes 735 | ///----------------------------- 736 | 737 | /** Last error message 738 | 739 | Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. 740 | 741 | @return `NSString` of the last error message. 742 | 743 | @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html) 744 | @see lastErrorCode 745 | @see lastError 746 | 747 | */ 748 | 749 | - (NSString*)lastErrorMessage; 750 | 751 | /** Last error code 752 | 753 | Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. 754 | 755 | @return Integer value of the last error code. 756 | 757 | @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) 758 | @see lastErrorMessage 759 | @see lastError 760 | 761 | */ 762 | 763 | - (int)lastErrorCode; 764 | 765 | /** Had error 766 | 767 | @return `YES` if there was an error, `NO` if no error. 768 | 769 | @see lastError 770 | @see lastErrorCode 771 | @see lastErrorMessage 772 | 773 | */ 774 | 775 | - (BOOL)hadError; 776 | 777 | /** Last error 778 | 779 | @return `NSError` representing the last error. 780 | 781 | @see lastErrorCode 782 | @see lastErrorMessage 783 | 784 | */ 785 | 786 | - (NSError*)lastError; 787 | 788 | 789 | // description forthcoming 790 | - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds; 791 | - (NSTimeInterval)maxBusyRetryTimeInterval; 792 | 793 | 794 | #if SQLITE_VERSION_NUMBER >= 3007000 795 | 796 | ///------------------ 797 | /// @name Save points 798 | ///------------------ 799 | 800 | /** Start save point 801 | 802 | @param name Name of save point. 803 | 804 | @param outErr A `NSError` object to receive any error object (if any). 805 | 806 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 807 | 808 | @see releaseSavePointWithName:error: 809 | @see rollbackToSavePointWithName:error: 810 | */ 811 | 812 | - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr; 813 | 814 | /** Release save point 815 | 816 | @param name Name of save point. 817 | 818 | @param outErr A `NSError` object to receive any error object (if any). 819 | 820 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 821 | 822 | @see startSavePointWithName:error: 823 | @see rollbackToSavePointWithName:error: 824 | 825 | */ 826 | 827 | - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr; 828 | 829 | /** Roll back to save point 830 | 831 | @param name Name of save point. 832 | @param outErr A `NSError` object to receive any error object (if any). 833 | 834 | @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. 835 | 836 | @see startSavePointWithName:error: 837 | @see releaseSavePointWithName:error: 838 | 839 | */ 840 | 841 | - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr; 842 | 843 | /** Start save point 844 | 845 | @param block Block of code to perform from within save point. 846 | 847 | @return The NSError corresponding to the error, if any. If no error, returns `nil`. 848 | 849 | @see startSavePointWithName:error: 850 | @see releaseSavePointWithName:error: 851 | @see rollbackToSavePointWithName:error: 852 | 853 | */ 854 | 855 | - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block; 856 | 857 | #endif 858 | 859 | ///---------------------------- 860 | /// @name SQLite library status 861 | ///---------------------------- 862 | 863 | /** Test to see if the library is threadsafe 864 | 865 | @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. 866 | 867 | @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html) 868 | */ 869 | 870 | + (BOOL)isSQLiteThreadSafe; 871 | 872 | /** Run-time library version numbers 873 | 874 | @return The sqlite library version string. 875 | 876 | @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html) 877 | */ 878 | 879 | + (NSString*)sqliteLibVersion; 880 | 881 | 882 | + (NSString*)FMDBUserVersion; 883 | 884 | + (SInt32)FMDBVersion; 885 | 886 | 887 | ///------------------------ 888 | /// @name Make SQL function 889 | ///------------------------ 890 | 891 | /** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. 892 | 893 | For example: 894 | 895 | [queue inDatabase:^(FMDatabase *adb) { 896 | 897 | [adb executeUpdate:@"create table ftest (foo text)"]; 898 | [adb executeUpdate:@"insert into ftest values ('hello')"]; 899 | [adb executeUpdate:@"insert into ftest values ('hi')"]; 900 | [adb executeUpdate:@"insert into ftest values ('not h!')"]; 901 | [adb executeUpdate:@"insert into ftest values ('definitely not h!')"]; 902 | 903 | [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) { 904 | if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { 905 | @autoreleasepool { 906 | const char *c = (const char *)sqlite3_value_text(aargv[0]); 907 | NSString *s = [NSString stringWithUTF8String:c]; 908 | sqlite3_result_int(context, [s hasPrefix:@"h"]); 909 | } 910 | } 911 | else { 912 | NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__); 913 | sqlite3_result_null(context); 914 | } 915 | }]; 916 | 917 | int rowCount = 0; 918 | FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; 919 | while ([ars next]) { 920 | rowCount++; 921 | NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]); 922 | } 923 | FMDBQuickCheck(rowCount == 2); 924 | }]; 925 | 926 | @param name Name of function 927 | 928 | @param count Maximum number of parameters 929 | 930 | @param block The block of code for the function 931 | 932 | @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html) 933 | */ 934 | 935 | - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block; 936 | 937 | 938 | ///--------------------- 939 | /// @name Date formatter 940 | ///--------------------- 941 | 942 | /** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. 943 | 944 | Use this method to generate values to set the dateFormat property. 945 | 946 | Example: 947 | 948 | myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 949 | 950 | @param format A valid NSDateFormatter format string. 951 | 952 | @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa. 953 | 954 | @see hasDateFormatter 955 | @see setDateFormat: 956 | @see dateFromString: 957 | @see stringFromDate: 958 | @see storeableDateFormat: 959 | 960 | @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes. 961 | 962 | */ 963 | 964 | + (NSDateFormatter *)storeableDateFormat:(NSString *)format; 965 | 966 | /** Test whether the database has a date formatter assigned. 967 | 968 | @return `YES` if there is a date formatter; `NO` if not. 969 | 970 | @see hasDateFormatter 971 | @see setDateFormat: 972 | @see dateFromString: 973 | @see stringFromDate: 974 | @see storeableDateFormat: 975 | */ 976 | 977 | - (BOOL)hasDateFormatter; 978 | 979 | /** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. 980 | 981 | @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat. 982 | 983 | @see hasDateFormatter 984 | @see setDateFormat: 985 | @see dateFromString: 986 | @see stringFromDate: 987 | @see storeableDateFormat: 988 | 989 | @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. 990 | */ 991 | 992 | - (void)setDateFormat:(NSDateFormatter *)format; 993 | 994 | /** Convert the supplied NSString to NSDate, using the current database formatter. 995 | 996 | @param s `NSString` to convert to `NSDate`. 997 | 998 | @return The `NSDate` object; or `nil` if no formatter is set. 999 | 1000 | @see hasDateFormatter 1001 | @see setDateFormat: 1002 | @see dateFromString: 1003 | @see stringFromDate: 1004 | @see storeableDateFormat: 1005 | */ 1006 | 1007 | - (NSDate *)dateFromString:(NSString *)s; 1008 | 1009 | /** Convert the supplied NSDate to NSString, using the current database formatter. 1010 | 1011 | @param date `NSDate` of date to convert to `NSString`. 1012 | 1013 | @return The `NSString` representation of the date; `nil` if no formatter is set. 1014 | 1015 | @see hasDateFormatter 1016 | @see setDateFormat: 1017 | @see dateFromString: 1018 | @see stringFromDate: 1019 | @see storeableDateFormat: 1020 | */ 1021 | 1022 | - (NSString *)stringFromDate:(NSDate *)date; 1023 | 1024 | @end 1025 | 1026 | 1027 | /** Objective-C wrapper for `sqlite3_stmt` 1028 | 1029 | This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `` and `` only. 1030 | 1031 | ### See also 1032 | 1033 | - `` 1034 | - `` 1035 | - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) 1036 | */ 1037 | 1038 | @interface FMStatement : NSObject { 1039 | sqlite3_stmt *_statement; 1040 | NSString *_query; 1041 | long _useCount; 1042 | BOOL _inUse; 1043 | } 1044 | 1045 | ///----------------- 1046 | /// @name Properties 1047 | ///----------------- 1048 | 1049 | /** Usage count */ 1050 | 1051 | @property (atomic, assign) long useCount; 1052 | 1053 | /** SQL statement */ 1054 | 1055 | @property (atomic, retain) NSString *query; 1056 | 1057 | /** SQLite sqlite3_stmt 1058 | 1059 | @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) 1060 | */ 1061 | 1062 | @property (atomic, assign) sqlite3_stmt *statement; 1063 | 1064 | /** Indication of whether the statement is in use */ 1065 | 1066 | @property (atomic, assign) BOOL inUse; 1067 | 1068 | ///---------------------------- 1069 | /// @name Closing and Resetting 1070 | ///---------------------------- 1071 | 1072 | /** Close statement */ 1073 | 1074 | - (void)close; 1075 | 1076 | /** Reset statement */ 1077 | 1078 | - (void)reset; 1079 | 1080 | @end 1081 | 1082 | #pragma clang diagnostic pop 1083 | 1084 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDatabaseAdditions.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseAdditions.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 10/30/05. 6 | // Copyright 2005 Flying Meat Inc.. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "FMDatabase.h" 11 | 12 | 13 | /** Category of additions for `` class. 14 | 15 | ### See also 16 | 17 | - `` 18 | */ 19 | 20 | @interface FMDatabase (FMDatabaseAdditions) 21 | 22 | ///---------------------------------------- 23 | /// @name Return results of SQL to variable 24 | ///---------------------------------------- 25 | 26 | /** Return `int` value for query 27 | 28 | @param query The SQL query to be performed. 29 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 30 | 31 | @return `int` value. 32 | 33 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 34 | */ 35 | 36 | - (int)intForQuery:(NSString*)query, ...; 37 | 38 | /** Return `long` value for query 39 | 40 | @param query The SQL query to be performed. 41 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 42 | 43 | @return `long` value. 44 | 45 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 46 | */ 47 | 48 | - (long)longForQuery:(NSString*)query, ...; 49 | 50 | /** Return `BOOL` value for query 51 | 52 | @param query The SQL query to be performed. 53 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 54 | 55 | @return `BOOL` value. 56 | 57 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 58 | */ 59 | 60 | - (BOOL)boolForQuery:(NSString*)query, ...; 61 | 62 | /** Return `double` value for query 63 | 64 | @param query The SQL query to be performed. 65 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 66 | 67 | @return `double` value. 68 | 69 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 70 | */ 71 | 72 | - (double)doubleForQuery:(NSString*)query, ...; 73 | 74 | /** Return `NSString` value for query 75 | 76 | @param query The SQL query to be performed. 77 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 78 | 79 | @return `NSString` value. 80 | 81 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 82 | */ 83 | 84 | - (NSString*)stringForQuery:(NSString*)query, ...; 85 | 86 | /** Return `NSData` value for query 87 | 88 | @param query The SQL query to be performed. 89 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 90 | 91 | @return `NSData` value. 92 | 93 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 94 | */ 95 | 96 | - (NSData*)dataForQuery:(NSString*)query, ...; 97 | 98 | /** Return `NSDate` value for query 99 | 100 | @param query The SQL query to be performed. 101 | @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. 102 | 103 | @return `NSDate` value. 104 | 105 | @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. 106 | */ 107 | 108 | - (NSDate*)dateForQuery:(NSString*)query, ...; 109 | 110 | 111 | // Notice that there's no dataNoCopyForQuery:. 112 | // That would be a bad idea, because we close out the result set, and then what 113 | // happens to the data that we just didn't copy? Who knows, not I. 114 | 115 | 116 | ///-------------------------------- 117 | /// @name Schema related operations 118 | ///-------------------------------- 119 | 120 | /** Does table exist in database? 121 | 122 | @param tableName The name of the table being looked for. 123 | 124 | @return `YES` if table found; `NO` if not found. 125 | */ 126 | 127 | - (BOOL)tableExists:(NSString*)tableName; 128 | 129 | /** The schema of the database. 130 | 131 | This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: 132 | 133 | - `type` - The type of entity (e.g. table, index, view, or trigger) 134 | - `name` - The name of the object 135 | - `tbl_name` - The name of the table to which the object references 136 | - `rootpage` - The page number of the root b-tree page for tables and indices 137 | - `sql` - The SQL that created the entity 138 | 139 | @return `FMResultSet` of schema; `nil` on error. 140 | 141 | @see [SQLite File Format](http://www.sqlite.org/fileformat.html) 142 | */ 143 | 144 | - (FMResultSet*)getSchema; 145 | 146 | /** The schema of the database. 147 | 148 | This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: 149 | 150 | PRAGMA table_info('employees') 151 | 152 | This will report: 153 | 154 | - `cid` - The column ID number 155 | - `name` - The name of the column 156 | - `type` - The data type specified for the column 157 | - `notnull` - whether the field is defined as NOT NULL (i.e. values required) 158 | - `dflt_value` - The default value for the column 159 | - `pk` - Whether the field is part of the primary key of the table 160 | 161 | @param tableName The name of the table for whom the schema will be returned. 162 | 163 | @return `FMResultSet` of schema; `nil` on error. 164 | 165 | @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info) 166 | */ 167 | 168 | - (FMResultSet*)getTableSchema:(NSString*)tableName; 169 | 170 | /** Test to see if particular column exists for particular table in database 171 | 172 | @param columnName The name of the column. 173 | 174 | @param tableName The name of the table. 175 | 176 | @return `YES` if column exists in table in question; `NO` otherwise. 177 | */ 178 | 179 | - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; 180 | 181 | /** Test to see if particular column exists for particular table in database 182 | 183 | @param columnName The name of the column. 184 | 185 | @param tableName The name of the table. 186 | 187 | @return `YES` if column exists in table in question; `NO` otherwise. 188 | 189 | @see columnExists:inTableWithName: 190 | 191 | @warning Deprecated - use `` instead. 192 | */ 193 | 194 | - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)); 195 | 196 | 197 | /** Validate SQL statement 198 | 199 | This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. 200 | 201 | @param sql The SQL statement being validated. 202 | 203 | @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. 204 | 205 | @return `YES` if validation succeeded without incident; `NO` otherwise. 206 | 207 | */ 208 | 209 | - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error; 210 | 211 | 212 | #if SQLITE_VERSION_NUMBER >= 3007017 213 | 214 | ///----------------------------------- 215 | /// @name Application identifier tasks 216 | ///----------------------------------- 217 | 218 | /** Retrieve application ID 219 | 220 | @return The `uint32_t` numeric value of the application ID. 221 | 222 | @see setApplicationID: 223 | */ 224 | 225 | - (uint32_t)applicationID; 226 | 227 | /** Set the application ID 228 | 229 | @param appID The `uint32_t` numeric value of the application ID. 230 | 231 | @see applicationID 232 | */ 233 | 234 | - (void)setApplicationID:(uint32_t)appID; 235 | 236 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 237 | /** Retrieve application ID string 238 | 239 | @return The `NSString` value of the application ID. 240 | 241 | @see setApplicationIDString: 242 | */ 243 | 244 | 245 | - (NSString*)applicationIDString; 246 | 247 | /** Set the application ID string 248 | 249 | @param string The `NSString` value of the application ID. 250 | 251 | @see applicationIDString 252 | */ 253 | 254 | - (void)setApplicationIDString:(NSString*)string; 255 | #endif 256 | 257 | #endif 258 | 259 | ///----------------------------------- 260 | /// @name user version identifier tasks 261 | ///----------------------------------- 262 | 263 | /** Retrieve user version 264 | 265 | @return The `uint32_t` numeric value of the user version. 266 | 267 | @see setUserVersion: 268 | */ 269 | 270 | - (uint32_t)userVersion; 271 | 272 | /** Set the user-version 273 | 274 | @param version The `uint32_t` numeric value of the user version. 275 | 276 | @see userVersion 277 | */ 278 | 279 | - (void)setUserVersion:(uint32_t)version; 280 | 281 | @end 282 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDatabaseAdditions.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseAdditions.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 10/30/05. 6 | // Copyright 2005 Flying Meat Inc.. All rights reserved. 7 | // 8 | 9 | #import "FMDatabase.h" 10 | #import "FMDatabaseAdditions.h" 11 | #import "TargetConditionals.h" 12 | 13 | @interface FMDatabase (PrivateStuff) 14 | - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; 15 | @end 16 | 17 | @implementation FMDatabase (FMDatabaseAdditions) 18 | 19 | #define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ 20 | va_list args; \ 21 | va_start(args, query); \ 22 | FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \ 23 | va_end(args); \ 24 | if (![resultSet next]) { return (type)0; } \ 25 | type ret = [resultSet sel:0]; \ 26 | [resultSet close]; \ 27 | [resultSet setParentDB:nil]; \ 28 | return ret; 29 | 30 | 31 | - (NSString*)stringForQuery:(NSString*)query, ... { 32 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); 33 | } 34 | 35 | - (int)intForQuery:(NSString*)query, ... { 36 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); 37 | } 38 | 39 | - (long)longForQuery:(NSString*)query, ... { 40 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); 41 | } 42 | 43 | - (BOOL)boolForQuery:(NSString*)query, ... { 44 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); 45 | } 46 | 47 | - (double)doubleForQuery:(NSString*)query, ... { 48 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); 49 | } 50 | 51 | - (NSData*)dataForQuery:(NSString*)query, ... { 52 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); 53 | } 54 | 55 | - (NSDate*)dateForQuery:(NSString*)query, ... { 56 | RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); 57 | } 58 | 59 | 60 | - (BOOL)tableExists:(NSString*)tableName { 61 | 62 | tableName = [tableName lowercaseString]; 63 | 64 | FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; 65 | 66 | //if at least one next exists, table exists 67 | BOOL returnBool = [rs next]; 68 | 69 | //close and free object 70 | [rs close]; 71 | 72 | return returnBool; 73 | } 74 | 75 | /* 76 | get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] 77 | check if table exist in database (patch from OZLB) 78 | */ 79 | - (FMResultSet*)getSchema { 80 | 81 | //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] 82 | FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; 83 | 84 | return rs; 85 | } 86 | 87 | /* 88 | get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] 89 | */ 90 | - (FMResultSet*)getTableSchema:(NSString*)tableName { 91 | 92 | //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] 93 | FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; 94 | 95 | return rs; 96 | } 97 | 98 | - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { 99 | 100 | BOOL returnBool = NO; 101 | 102 | tableName = [tableName lowercaseString]; 103 | columnName = [columnName lowercaseString]; 104 | 105 | FMResultSet *rs = [self getTableSchema:tableName]; 106 | 107 | //check if column is present in table schema 108 | while ([rs next]) { 109 | if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { 110 | returnBool = YES; 111 | break; 112 | } 113 | } 114 | 115 | //If this is not done FMDatabase instance stays out of pool 116 | [rs close]; 117 | 118 | return returnBool; 119 | } 120 | 121 | 122 | #if SQLITE_VERSION_NUMBER >= 3007017 123 | 124 | - (uint32_t)applicationID { 125 | 126 | uint32_t r = 0; 127 | 128 | FMResultSet *rs = [self executeQuery:@"pragma application_id"]; 129 | 130 | if ([rs next]) { 131 | r = (uint32_t)[rs longLongIntForColumnIndex:0]; 132 | } 133 | 134 | [rs close]; 135 | 136 | return r; 137 | } 138 | 139 | - (void)setApplicationID:(uint32_t)appID { 140 | NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; 141 | FMResultSet *rs = [self executeQuery:query]; 142 | [rs next]; 143 | [rs close]; 144 | } 145 | 146 | 147 | #if TARGET_OS_MAC && !TARGET_OS_IPHONE 148 | - (NSString*)applicationIDString { 149 | NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); 150 | 151 | assert([s length] == 6); 152 | 153 | s = [s substringWithRange:NSMakeRange(1, 4)]; 154 | 155 | 156 | return s; 157 | 158 | } 159 | 160 | - (void)setApplicationIDString:(NSString*)s { 161 | 162 | if ([s length] != 4) { 163 | NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); 164 | } 165 | 166 | [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; 167 | } 168 | 169 | 170 | #endif 171 | 172 | #endif 173 | 174 | - (uint32_t)userVersion { 175 | uint32_t r = 0; 176 | 177 | FMResultSet *rs = [self executeQuery:@"pragma user_version"]; 178 | 179 | if ([rs next]) { 180 | r = (uint32_t)[rs longLongIntForColumnIndex:0]; 181 | } 182 | 183 | [rs close]; 184 | return r; 185 | } 186 | 187 | - (void)setUserVersion:(uint32_t)version { 188 | NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; 189 | FMResultSet *rs = [self executeQuery:query]; 190 | [rs next]; 191 | [rs close]; 192 | } 193 | 194 | #pragma clang diagnostic push 195 | #pragma clang diagnostic ignored "-Wdeprecated-implementations" 196 | 197 | - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { 198 | return [self columnExists:columnName inTableWithName:tableName]; 199 | } 200 | 201 | #pragma clang diagnostic pop 202 | 203 | 204 | - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error { 205 | sqlite3_stmt *pStmt = NULL; 206 | BOOL validationSucceeded = YES; 207 | 208 | int rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); 209 | if (rc != SQLITE_OK) { 210 | validationSucceeded = NO; 211 | if (error) { 212 | *error = [NSError errorWithDomain:NSCocoaErrorDomain 213 | code:[self lastErrorCode] 214 | userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] 215 | forKey:NSLocalizedDescriptionKey]]; 216 | } 217 | } 218 | 219 | sqlite3_finalize(pStmt); 220 | 221 | return validationSucceeded; 222 | } 223 | 224 | @end 225 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDatabasePool.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabasePool.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "sqlite3.h" 11 | 12 | @class FMDatabase; 13 | 14 | /** Pool of `` objects. 15 | 16 | ### See also 17 | 18 | - `` 19 | - `` 20 | 21 | @warning Before using `FMDatabasePool`, please consider using `` instead. 22 | 23 | If you really really really know what you're doing and `FMDatabasePool` is what 24 | you really really need (ie, you're using a read only database), OK you can use 25 | it. But just be careful not to deadlock! 26 | 27 | For an example on deadlocking, search for: 28 | `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD` 29 | in the main.m file. 30 | */ 31 | 32 | @interface FMDatabasePool : NSObject { 33 | NSString *_path; 34 | 35 | dispatch_queue_t _lockQueue; 36 | 37 | NSMutableArray *_databaseInPool; 38 | NSMutableArray *_databaseOutPool; 39 | 40 | __unsafe_unretained id _delegate; 41 | 42 | NSUInteger _maximumNumberOfDatabasesToCreate; 43 | int _openFlags; 44 | } 45 | 46 | /** Database path */ 47 | 48 | @property (atomic, retain) NSString *path; 49 | 50 | /** Delegate object */ 51 | 52 | @property (atomic, assign) id delegate; 53 | 54 | /** Maximum number of databases to create */ 55 | 56 | @property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; 57 | 58 | /** Open flags */ 59 | 60 | @property (atomic, readonly) int openFlags; 61 | 62 | 63 | ///--------------------- 64 | /// @name Initialization 65 | ///--------------------- 66 | 67 | /** Create pool using path. 68 | 69 | @param aPath The file path of the database. 70 | 71 | @return The `FMDatabasePool` object. `nil` on error. 72 | */ 73 | 74 | + (instancetype)databasePoolWithPath:(NSString*)aPath; 75 | 76 | /** Create pool using path and specified flags 77 | 78 | @param aPath The file path of the database. 79 | @param openFlags Flags passed to the openWithFlags method of the database 80 | 81 | @return The `FMDatabasePool` object. `nil` on error. 82 | */ 83 | 84 | + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags; 85 | 86 | /** Create pool using path. 87 | 88 | @param aPath The file path of the database. 89 | 90 | @return The `FMDatabasePool` object. `nil` on error. 91 | */ 92 | 93 | - (instancetype)initWithPath:(NSString*)aPath; 94 | 95 | /** Create pool using path and specified flags. 96 | 97 | @param aPath The file path of the database. 98 | @param openFlags Flags passed to the openWithFlags method of the database 99 | 100 | @return The `FMDatabasePool` object. `nil` on error. 101 | */ 102 | 103 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; 104 | 105 | ///------------------------------------------------ 106 | /// @name Keeping track of checked in/out databases 107 | ///------------------------------------------------ 108 | 109 | /** Number of checked-in databases in pool 110 | 111 | @returns Number of databases 112 | */ 113 | 114 | - (NSUInteger)countOfCheckedInDatabases; 115 | 116 | /** Number of checked-out databases in pool 117 | 118 | @returns Number of databases 119 | */ 120 | 121 | - (NSUInteger)countOfCheckedOutDatabases; 122 | 123 | /** Total number of databases in pool 124 | 125 | @returns Number of databases 126 | */ 127 | 128 | - (NSUInteger)countOfOpenDatabases; 129 | 130 | /** Release all databases in pool */ 131 | 132 | - (void)releaseAllDatabases; 133 | 134 | ///------------------------------------------ 135 | /// @name Perform database operations in pool 136 | ///------------------------------------------ 137 | 138 | /** Synchronously perform database operations in pool. 139 | 140 | @param block The code to be run on the `FMDatabasePool` pool. 141 | */ 142 | 143 | - (void)inDatabase:(void (^)(FMDatabase *db))block; 144 | 145 | /** Synchronously perform database operations in pool using transaction. 146 | 147 | @param block The code to be run on the `FMDatabasePool` pool. 148 | */ 149 | 150 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 151 | 152 | /** Synchronously perform database operations in pool using deferred transaction. 153 | 154 | @param block The code to be run on the `FMDatabasePool` pool. 155 | */ 156 | 157 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 158 | 159 | #if SQLITE_VERSION_NUMBER >= 3007000 160 | 161 | /** Synchronously perform database operations in pool using save point. 162 | 163 | @param block The code to be run on the `FMDatabasePool` pool. 164 | 165 | @return `NSError` object if error; `nil` if successful. 166 | 167 | @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead. 168 | */ 169 | 170 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; 171 | #endif 172 | 173 | @end 174 | 175 | 176 | /** FMDatabasePool delegate category 177 | 178 | This is a category that defines the protocol for the FMDatabasePool delegate 179 | */ 180 | 181 | @interface NSObject (FMDatabasePoolDelegate) 182 | 183 | /** Asks the delegate whether database should be added to the pool. 184 | 185 | @param pool The `FMDatabasePool` object. 186 | @param database The `FMDatabase` object. 187 | 188 | @return `YES` if it should add database to pool; `NO` if not. 189 | 190 | */ 191 | 192 | - (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; 193 | 194 | /** Tells the delegate that database was added to the pool. 195 | 196 | @param pool The `FMDatabasePool` object. 197 | @param database The `FMDatabase` object. 198 | 199 | */ 200 | 201 | - (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; 202 | 203 | @end 204 | 205 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDatabasePool.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabasePool.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import "FMDatabasePool.h" 10 | #import "FMDatabase.h" 11 | 12 | @interface FMDatabasePool() 13 | 14 | - (void)pushDatabaseBackInPool:(FMDatabase*)db; 15 | - (FMDatabase*)db; 16 | 17 | @end 18 | 19 | 20 | @implementation FMDatabasePool 21 | @synthesize path=_path; 22 | @synthesize delegate=_delegate; 23 | @synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; 24 | @synthesize openFlags=_openFlags; 25 | 26 | 27 | + (instancetype)databasePoolWithPath:(NSString*)aPath { 28 | return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); 29 | } 30 | 31 | + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags { 32 | return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); 33 | } 34 | 35 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { 36 | 37 | self = [super init]; 38 | 39 | if (self != nil) { 40 | _path = [aPath copy]; 41 | _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); 42 | _databaseInPool = FMDBReturnRetained([NSMutableArray array]); 43 | _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); 44 | _openFlags = openFlags; 45 | } 46 | 47 | return self; 48 | } 49 | 50 | - (instancetype)initWithPath:(NSString*)aPath 51 | { 52 | // default flags for sqlite3_open 53 | return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; 54 | } 55 | 56 | - (instancetype)init { 57 | return [self initWithPath:nil]; 58 | } 59 | 60 | 61 | - (void)dealloc { 62 | 63 | _delegate = 0x00; 64 | FMDBRelease(_path); 65 | FMDBRelease(_databaseInPool); 66 | FMDBRelease(_databaseOutPool); 67 | 68 | if (_lockQueue) { 69 | FMDBDispatchQueueRelease(_lockQueue); 70 | _lockQueue = 0x00; 71 | } 72 | #if ! __has_feature(objc_arc) 73 | [super dealloc]; 74 | #endif 75 | } 76 | 77 | 78 | - (void)executeLocked:(void (^)(void))aBlock { 79 | dispatch_sync(_lockQueue, aBlock); 80 | } 81 | 82 | - (void)pushDatabaseBackInPool:(FMDatabase*)db { 83 | 84 | if (!db) { // db can be null if we set an upper bound on the # of databases to create. 85 | return; 86 | } 87 | 88 | [self executeLocked:^() { 89 | 90 | if ([self->_databaseInPool containsObject:db]) { 91 | [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; 92 | } 93 | 94 | [self->_databaseInPool addObject:db]; 95 | [self->_databaseOutPool removeObject:db]; 96 | 97 | }]; 98 | } 99 | 100 | - (FMDatabase*)db { 101 | 102 | __block FMDatabase *db; 103 | 104 | 105 | [self executeLocked:^() { 106 | db = [self->_databaseInPool lastObject]; 107 | 108 | BOOL shouldNotifyDelegate = NO; 109 | 110 | if (db) { 111 | [self->_databaseOutPool addObject:db]; 112 | [self->_databaseInPool removeLastObject]; 113 | } 114 | else { 115 | 116 | if (self->_maximumNumberOfDatabasesToCreate) { 117 | NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count]; 118 | 119 | if (currentCount >= self->_maximumNumberOfDatabasesToCreate) { 120 | NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); 121 | return; 122 | } 123 | } 124 | 125 | db = [FMDatabase databaseWithPath:self->_path]; 126 | shouldNotifyDelegate = YES; 127 | } 128 | 129 | //This ensures that the db is opened before returning 130 | #if SQLITE_VERSION_NUMBER >= 3005000 131 | BOOL success = [db openWithFlags:self->_openFlags]; 132 | #else 133 | BOOL success = [db open]; 134 | #endif 135 | if (success) { 136 | if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) { 137 | [db close]; 138 | db = 0x00; 139 | } 140 | else { 141 | //It should not get added in the pool twice if lastObject was found 142 | if (![self->_databaseOutPool containsObject:db]) { 143 | [self->_databaseOutPool addObject:db]; 144 | 145 | if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { 146 | [self->_delegate databasePool:self didAddDatabase:db]; 147 | } 148 | } 149 | } 150 | } 151 | else { 152 | NSLog(@"Could not open up the database at path %@", self->_path); 153 | db = 0x00; 154 | } 155 | }]; 156 | 157 | return db; 158 | } 159 | 160 | - (NSUInteger)countOfCheckedInDatabases { 161 | 162 | __block NSUInteger count; 163 | 164 | [self executeLocked:^() { 165 | count = [self->_databaseInPool count]; 166 | }]; 167 | 168 | return count; 169 | } 170 | 171 | - (NSUInteger)countOfCheckedOutDatabases { 172 | 173 | __block NSUInteger count; 174 | 175 | [self executeLocked:^() { 176 | count = [self->_databaseOutPool count]; 177 | }]; 178 | 179 | return count; 180 | } 181 | 182 | - (NSUInteger)countOfOpenDatabases { 183 | __block NSUInteger count; 184 | 185 | [self executeLocked:^() { 186 | count = [self->_databaseOutPool count] + [self->_databaseInPool count]; 187 | }]; 188 | 189 | return count; 190 | } 191 | 192 | - (void)releaseAllDatabases { 193 | [self executeLocked:^() { 194 | [self->_databaseOutPool removeAllObjects]; 195 | [self->_databaseInPool removeAllObjects]; 196 | }]; 197 | } 198 | 199 | - (void)inDatabase:(void (^)(FMDatabase *db))block { 200 | 201 | FMDatabase *db = [self db]; 202 | 203 | block(db); 204 | 205 | [self pushDatabaseBackInPool:db]; 206 | } 207 | 208 | - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { 209 | 210 | BOOL shouldRollback = NO; 211 | 212 | FMDatabase *db = [self db]; 213 | 214 | if (useDeferred) { 215 | [db beginDeferredTransaction]; 216 | } 217 | else { 218 | [db beginTransaction]; 219 | } 220 | 221 | 222 | block(db, &shouldRollback); 223 | 224 | if (shouldRollback) { 225 | [db rollback]; 226 | } 227 | else { 228 | [db commit]; 229 | } 230 | 231 | [self pushDatabaseBackInPool:db]; 232 | } 233 | 234 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 235 | [self beginTransaction:YES withBlock:block]; 236 | } 237 | 238 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 239 | [self beginTransaction:NO withBlock:block]; 240 | } 241 | #if SQLITE_VERSION_NUMBER >= 3007000 242 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { 243 | 244 | static unsigned long savePointIdx = 0; 245 | 246 | NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; 247 | 248 | BOOL shouldRollback = NO; 249 | 250 | FMDatabase *db = [self db]; 251 | 252 | NSError *err = 0x00; 253 | 254 | if (![db startSavePointWithName:name error:&err]) { 255 | [self pushDatabaseBackInPool:db]; 256 | return err; 257 | } 258 | 259 | block(db, &shouldRollback); 260 | 261 | if (shouldRollback) { 262 | // We need to rollback and release this savepoint to remove it 263 | [db rollbackToSavePointWithName:name error:&err]; 264 | } 265 | [db releaseSavePointWithName:name error:&err]; 266 | 267 | [self pushDatabaseBackInPool:db]; 268 | 269 | return err; 270 | } 271 | #endif 272 | 273 | @end 274 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDatabaseQueue.h: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseQueue.h 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "sqlite3.h" 11 | 12 | @class FMDatabase; 13 | 14 | /** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. 15 | 16 | Using a single instance of `` from multiple threads at once is a bad idea. It has always been OK to make a `` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. 17 | 18 | Instead, use `FMDatabaseQueue`. Here's how to use it: 19 | 20 | First, make your queue. 21 | 22 | FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; 23 | 24 | Then use it like so: 25 | 26 | [queue inDatabase:^(FMDatabase *db) { 27 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 28 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 29 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; 30 | 31 | FMResultSet *rs = [db executeQuery:@"select * from foo"]; 32 | while ([rs next]) { 33 | //… 34 | } 35 | }]; 36 | 37 | An easy way to wrap things up in a transaction can be done like this: 38 | 39 | [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { 40 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; 41 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; 42 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; 43 | 44 | if (whoopsSomethingWrongHappened) { 45 | *rollback = YES; 46 | return; 47 | } 48 | // etc… 49 | [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; 50 | }]; 51 | 52 | `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. 53 | 54 | ### See also 55 | 56 | - `` 57 | 58 | @warning Do not instantiate a single `` object and use it across multiple threads. Use `FMDatabaseQueue` instead. 59 | 60 | @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. 61 | 62 | */ 63 | 64 | @interface FMDatabaseQueue : NSObject { 65 | NSString *_path; 66 | dispatch_queue_t _queue; 67 | FMDatabase *_db; 68 | int _openFlags; 69 | } 70 | 71 | /** Path of database */ 72 | 73 | @property (atomic, retain) NSString *path; 74 | 75 | /** Open flags */ 76 | 77 | @property (atomic, readonly) int openFlags; 78 | 79 | ///---------------------------------------------------- 80 | /// @name Initialization, opening, and closing of queue 81 | ///---------------------------------------------------- 82 | 83 | /** Create queue using path. 84 | 85 | @param aPath The file path of the database. 86 | 87 | @return The `FMDatabaseQueue` object. `nil` on error. 88 | */ 89 | 90 | + (instancetype)databaseQueueWithPath:(NSString*)aPath; 91 | 92 | /** Create queue using path and specified flags. 93 | 94 | @param aPath The file path of the database. 95 | @param openFlags Flags passed to the openWithFlags method of the database 96 | 97 | @return The `FMDatabaseQueue` object. `nil` on error. 98 | */ 99 | + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags; 100 | 101 | /** Create queue using path. 102 | 103 | @param aPath The file path of the database. 104 | 105 | @return The `FMDatabaseQueue` object. `nil` on error. 106 | */ 107 | 108 | - (instancetype)initWithPath:(NSString*)aPath; 109 | 110 | /** Create queue using path and specified flags. 111 | 112 | @param aPath The file path of the database. 113 | @param openFlags Flags passed to the openWithFlags method of the database 114 | 115 | @return The `FMDatabaseQueue` object. `nil` on error. 116 | */ 117 | 118 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; 119 | 120 | /** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. 121 | 122 | Subclasses can override this method to return specified Class of 'FMDatabase' subclass. 123 | 124 | @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. 125 | */ 126 | 127 | + (Class)databaseClass; 128 | 129 | /** Close database used by queue. */ 130 | 131 | - (void)close; 132 | 133 | ///----------------------------------------------- 134 | /// @name Dispatching database operations to queue 135 | ///----------------------------------------------- 136 | 137 | /** Synchronously perform database operations on queue. 138 | 139 | @param block The code to be run on the queue of `FMDatabaseQueue` 140 | */ 141 | 142 | - (void)inDatabase:(void (^)(FMDatabase *db))block; 143 | 144 | /** Synchronously perform database operations on queue, using transactions. 145 | 146 | @param block The code to be run on the queue of `FMDatabaseQueue` 147 | */ 148 | 149 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 150 | 151 | /** Synchronously perform database operations on queue, using deferred transactions. 152 | 153 | @param block The code to be run on the queue of `FMDatabaseQueue` 154 | */ 155 | 156 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; 157 | 158 | ///----------------------------------------------- 159 | /// @name Dispatching database operations to queue 160 | ///----------------------------------------------- 161 | 162 | /** Synchronously perform database operations using save point. 163 | 164 | @param block The code to be run on the queue of `FMDatabaseQueue` 165 | */ 166 | 167 | #if SQLITE_VERSION_NUMBER >= 3007000 168 | // NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. 169 | // If you need to nest, use FMDatabase's startSavePointWithName:error: instead. 170 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; 171 | #endif 172 | 173 | @end 174 | 175 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMDatabaseQueue.m: -------------------------------------------------------------------------------- 1 | // 2 | // FMDatabaseQueue.m 3 | // fmdb 4 | // 5 | // Created by August Mueller on 6/22/11. 6 | // Copyright 2011 Flying Meat Inc. All rights reserved. 7 | // 8 | 9 | #import "FMDatabaseQueue.h" 10 | #import "FMDatabase.h" 11 | 12 | /* 13 | 14 | Note: we call [self retain]; before using dispatch_sync, just incase 15 | FMDatabaseQueue is released on another thread and we're in the middle of doing 16 | something in dispatch_sync 17 | 18 | */ 19 | 20 | /* 21 | * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. 22 | * This in turn is used for deadlock detection by seeing if inDatabase: is called on 23 | * the queue's dispatch queue, which should not happen and causes a deadlock. 24 | */ 25 | static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; 26 | 27 | @implementation FMDatabaseQueue 28 | 29 | @synthesize path = _path; 30 | @synthesize openFlags = _openFlags; 31 | 32 | + (instancetype)databaseQueueWithPath:(NSString*)aPath { 33 | 34 | FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; 35 | 36 | FMDBAutorelease(q); 37 | 38 | return q; 39 | } 40 | 41 | + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags { 42 | 43 | FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; 44 | 45 | FMDBAutorelease(q); 46 | 47 | return q; 48 | } 49 | 50 | + (Class)databaseClass { 51 | return [FMDatabase class]; 52 | } 53 | 54 | - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { 55 | 56 | self = [super init]; 57 | 58 | if (self != nil) { 59 | 60 | _db = [[[self class] databaseClass] databaseWithPath:aPath]; 61 | FMDBRetain(_db); 62 | 63 | #if SQLITE_VERSION_NUMBER >= 3005000 64 | BOOL success = [_db openWithFlags:openFlags]; 65 | #else 66 | BOOL success = [_db open]; 67 | #endif 68 | if (!success) { 69 | NSLog(@"Could not create database queue for path %@", aPath); 70 | FMDBRelease(self); 71 | return 0x00; 72 | } 73 | 74 | _path = FMDBReturnRetained(aPath); 75 | 76 | _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); 77 | dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); 78 | _openFlags = openFlags; 79 | } 80 | 81 | return self; 82 | } 83 | 84 | - (instancetype)initWithPath:(NSString*)aPath { 85 | 86 | // default flags for sqlite3_open 87 | return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; 88 | } 89 | 90 | - (instancetype)init { 91 | return [self initWithPath:nil]; 92 | } 93 | 94 | 95 | - (void)dealloc { 96 | 97 | FMDBRelease(_db); 98 | FMDBRelease(_path); 99 | 100 | if (_queue) { 101 | FMDBDispatchQueueRelease(_queue); 102 | _queue = 0x00; 103 | } 104 | #if ! __has_feature(objc_arc) 105 | [super dealloc]; 106 | #endif 107 | } 108 | 109 | - (void)close { 110 | FMDBRetain(self); 111 | dispatch_sync(_queue, ^() { 112 | [self->_db close]; 113 | FMDBRelease(_db); 114 | self->_db = 0x00; 115 | }); 116 | FMDBRelease(self); 117 | } 118 | 119 | - (FMDatabase*)database { 120 | if (!_db) { 121 | _db = FMDBReturnRetained([FMDatabase databaseWithPath:_path]); 122 | 123 | #if SQLITE_VERSION_NUMBER >= 3005000 124 | BOOL success = [_db openWithFlags:_openFlags]; 125 | #else 126 | BOOL success = [_db open]; 127 | #endif 128 | if (!success) { 129 | NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); 130 | FMDBRelease(_db); 131 | _db = 0x00; 132 | return 0x00; 133 | } 134 | } 135 | 136 | return _db; 137 | } 138 | 139 | - (void)inDatabase:(void (^)(FMDatabase *db))block { 140 | /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue 141 | * and then check it against self to make sure we're not about to deadlock. */ 142 | FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); 143 | assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); 144 | 145 | FMDBRetain(self); 146 | 147 | dispatch_sync(_queue, ^() { 148 | 149 | FMDatabase *db = [self database]; 150 | block(db); 151 | 152 | if ([db hasOpenResultSets]) { 153 | NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); 154 | 155 | #if defined(DEBUG) && DEBUG 156 | NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); 157 | for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { 158 | FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; 159 | NSLog(@"query: '%@'", [rs query]); 160 | } 161 | #endif 162 | } 163 | }); 164 | 165 | FMDBRelease(self); 166 | } 167 | 168 | 169 | - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { 170 | FMDBRetain(self); 171 | dispatch_sync(_queue, ^() { 172 | 173 | BOOL shouldRollback = NO; 174 | 175 | if (useDeferred) { 176 | [[self database] beginDeferredTransaction]; 177 | } 178 | else { 179 | [[self database] beginTransaction]; 180 | } 181 | 182 | block([self database], &shouldRollback); 183 | 184 | if (shouldRollback) { 185 | [[self database] rollback]; 186 | } 187 | else { 188 | [[self database] commit]; 189 | } 190 | }); 191 | 192 | FMDBRelease(self); 193 | } 194 | 195 | - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 196 | [self beginTransaction:YES withBlock:block]; 197 | } 198 | 199 | - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { 200 | [self beginTransaction:NO withBlock:block]; 201 | } 202 | 203 | #if SQLITE_VERSION_NUMBER >= 3007000 204 | - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { 205 | 206 | static unsigned long savePointIdx = 0; 207 | __block NSError *err = 0x00; 208 | FMDBRetain(self); 209 | dispatch_sync(_queue, ^() { 210 | 211 | NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; 212 | 213 | BOOL shouldRollback = NO; 214 | 215 | if ([[self database] startSavePointWithName:name error:&err]) { 216 | 217 | block([self database], &shouldRollback); 218 | 219 | if (shouldRollback) { 220 | // We need to rollback and release this savepoint to remove it 221 | [[self database] rollbackToSavePointWithName:name error:&err]; 222 | } 223 | [[self database] releaseSavePointWithName:name error:&err]; 224 | 225 | } 226 | }); 227 | FMDBRelease(self); 228 | return err; 229 | } 230 | #endif 231 | 232 | @end 233 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMResultSet.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "sqlite3.h" 3 | 4 | #ifndef __has_feature // Optional. 5 | #define __has_feature(x) 0 // Compatibility with non-clang compilers. 6 | #endif 7 | 8 | #ifndef NS_RETURNS_NOT_RETAINED 9 | #if __has_feature(attribute_ns_returns_not_retained) 10 | #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) 11 | #else 12 | #define NS_RETURNS_NOT_RETAINED 13 | #endif 14 | #endif 15 | 16 | @class FMDatabase; 17 | @class FMStatement; 18 | 19 | /** Represents the results of executing a query on an ``. 20 | 21 | ### See also 22 | 23 | - `` 24 | */ 25 | 26 | @interface FMResultSet : NSObject { 27 | FMDatabase *_parentDB; 28 | FMStatement *_statement; 29 | 30 | NSString *_query; 31 | NSMutableDictionary *_columnNameToIndexMap; 32 | } 33 | 34 | ///----------------- 35 | /// @name Properties 36 | ///----------------- 37 | 38 | /** Executed query */ 39 | 40 | @property (atomic, retain) NSString *query; 41 | 42 | /** `NSMutableDictionary` mapping column names to numeric index */ 43 | 44 | @property (readonly) NSMutableDictionary *columnNameToIndexMap; 45 | 46 | /** `FMStatement` used by result set. */ 47 | 48 | @property (atomic, retain) FMStatement *statement; 49 | 50 | ///------------------------------------ 51 | /// @name Creating and closing database 52 | ///------------------------------------ 53 | 54 | /** Create result set from `` 55 | 56 | @param statement A `` to be performed 57 | 58 | @param aDB A `` to be used 59 | 60 | @return A `FMResultSet` on success; `nil` on failure 61 | */ 62 | 63 | + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; 64 | 65 | /** Close result set */ 66 | 67 | - (void)close; 68 | 69 | - (void)setParentDB:(FMDatabase *)newDb; 70 | 71 | ///--------------------------------------- 72 | /// @name Iterating through the result set 73 | ///--------------------------------------- 74 | 75 | /** Retrieve next row for result set. 76 | 77 | You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. 78 | 79 | @return `YES` if row successfully retrieved; `NO` if end of result set reached 80 | 81 | @see hasAnotherRow 82 | */ 83 | 84 | - (BOOL)next; 85 | 86 | /** Retrieve next row for result set. 87 | 88 | You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. 89 | 90 | @param outErr A 'NSError' object to receive any error object (if any). 91 | 92 | @return 'YES' if row successfully retrieved; 'NO' if end of result set reached 93 | 94 | @see hasAnotherRow 95 | */ 96 | 97 | - (BOOL)nextWithError:(NSError **)outErr; 98 | 99 | /** Did the last call to `` succeed in retrieving another row? 100 | 101 | @return `YES` if the last call to `` succeeded in retrieving another record; `NO` if not. 102 | 103 | @see next 104 | 105 | @warning The `hasAnotherRow` method must follow a call to ``. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not. 106 | */ 107 | 108 | - (BOOL)hasAnotherRow; 109 | 110 | ///--------------------------------------------- 111 | /// @name Retrieving information from result set 112 | ///--------------------------------------------- 113 | 114 | /** How many columns in result set 115 | 116 | @return Integer value of the number of columns. 117 | */ 118 | 119 | - (int)columnCount; 120 | 121 | /** Column index for column name 122 | 123 | @param columnName `NSString` value of the name of the column. 124 | 125 | @return Zero-based index for column. 126 | */ 127 | 128 | - (int)columnIndexForName:(NSString*)columnName; 129 | 130 | /** Column name for column index 131 | 132 | @param columnIdx Zero-based index for column. 133 | 134 | @return columnName `NSString` value of the name of the column. 135 | */ 136 | 137 | - (NSString*)columnNameForIndex:(int)columnIdx; 138 | 139 | /** Result set integer value for column. 140 | 141 | @param columnName `NSString` value of the name of the column. 142 | 143 | @return `int` value of the result set's column. 144 | */ 145 | 146 | - (int)intForColumn:(NSString*)columnName; 147 | 148 | /** Result set integer value for column. 149 | 150 | @param columnIdx Zero-based index for column. 151 | 152 | @return `int` value of the result set's column. 153 | */ 154 | 155 | - (int)intForColumnIndex:(int)columnIdx; 156 | 157 | /** Result set `long` value for column. 158 | 159 | @param columnName `NSString` value of the name of the column. 160 | 161 | @return `long` value of the result set's column. 162 | */ 163 | 164 | - (long)longForColumn:(NSString*)columnName; 165 | 166 | /** Result set long value for column. 167 | 168 | @param columnIdx Zero-based index for column. 169 | 170 | @return `long` value of the result set's column. 171 | */ 172 | 173 | - (long)longForColumnIndex:(int)columnIdx; 174 | 175 | /** Result set `long long int` value for column. 176 | 177 | @param columnName `NSString` value of the name of the column. 178 | 179 | @return `long long int` value of the result set's column. 180 | */ 181 | 182 | - (long long int)longLongIntForColumn:(NSString*)columnName; 183 | 184 | /** Result set `long long int` value for column. 185 | 186 | @param columnIdx Zero-based index for column. 187 | 188 | @return `long long int` value of the result set's column. 189 | */ 190 | 191 | - (long long int)longLongIntForColumnIndex:(int)columnIdx; 192 | 193 | /** Result set `unsigned long long int` value for column. 194 | 195 | @param columnName `NSString` value of the name of the column. 196 | 197 | @return `unsigned long long int` value of the result set's column. 198 | */ 199 | 200 | - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; 201 | 202 | /** Result set `unsigned long long int` value for column. 203 | 204 | @param columnIdx Zero-based index for column. 205 | 206 | @return `unsigned long long int` value of the result set's column. 207 | */ 208 | 209 | - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; 210 | 211 | /** Result set `BOOL` value for column. 212 | 213 | @param columnName `NSString` value of the name of the column. 214 | 215 | @return `BOOL` value of the result set's column. 216 | */ 217 | 218 | - (BOOL)boolForColumn:(NSString*)columnName; 219 | 220 | /** Result set `BOOL` value for column. 221 | 222 | @param columnIdx Zero-based index for column. 223 | 224 | @return `BOOL` value of the result set's column. 225 | */ 226 | 227 | - (BOOL)boolForColumnIndex:(int)columnIdx; 228 | 229 | /** Result set `double` value for column. 230 | 231 | @param columnName `NSString` value of the name of the column. 232 | 233 | @return `double` value of the result set's column. 234 | 235 | */ 236 | 237 | - (double)doubleForColumn:(NSString*)columnName; 238 | 239 | /** Result set `double` value for column. 240 | 241 | @param columnIdx Zero-based index for column. 242 | 243 | @return `double` value of the result set's column. 244 | 245 | */ 246 | 247 | - (double)doubleForColumnIndex:(int)columnIdx; 248 | 249 | /** Result set `NSString` value for column. 250 | 251 | @param columnName `NSString` value of the name of the column. 252 | 253 | @return `NSString` value of the result set's column. 254 | 255 | */ 256 | 257 | - (NSString*)stringForColumn:(NSString*)columnName; 258 | 259 | /** Result set `NSString` value for column. 260 | 261 | @param columnIdx Zero-based index for column. 262 | 263 | @return `NSString` value of the result set's column. 264 | */ 265 | 266 | - (NSString*)stringForColumnIndex:(int)columnIdx; 267 | 268 | /** Result set `NSDate` value for column. 269 | 270 | @param columnName `NSString` value of the name of the column. 271 | 272 | @return `NSDate` value of the result set's column. 273 | */ 274 | 275 | - (NSDate*)dateForColumn:(NSString*)columnName; 276 | 277 | /** Result set `NSDate` value for column. 278 | 279 | @param columnIdx Zero-based index for column. 280 | 281 | @return `NSDate` value of the result set's column. 282 | 283 | */ 284 | 285 | - (NSDate*)dateForColumnIndex:(int)columnIdx; 286 | 287 | /** Result set `NSData` value for column. 288 | 289 | This is useful when storing binary data in table (such as image or the like). 290 | 291 | @param columnName `NSString` value of the name of the column. 292 | 293 | @return `NSData` value of the result set's column. 294 | 295 | */ 296 | 297 | - (NSData*)dataForColumn:(NSString*)columnName; 298 | 299 | /** Result set `NSData` value for column. 300 | 301 | @param columnIdx Zero-based index for column. 302 | 303 | @return `NSData` value of the result set's column. 304 | */ 305 | 306 | - (NSData*)dataForColumnIndex:(int)columnIdx; 307 | 308 | /** Result set `(const unsigned char *)` value for column. 309 | 310 | @param columnName `NSString` value of the name of the column. 311 | 312 | @return `(const unsigned char *)` value of the result set's column. 313 | */ 314 | 315 | - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName; 316 | 317 | /** Result set `(const unsigned char *)` value for column. 318 | 319 | @param columnIdx Zero-based index for column. 320 | 321 | @return `(const unsigned char *)` value of the result set's column. 322 | */ 323 | 324 | - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx; 325 | 326 | /** Result set object for column. 327 | 328 | @param columnName `NSString` value of the name of the column. 329 | 330 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 331 | 332 | @see objectForKeyedSubscript: 333 | */ 334 | 335 | - (id)objectForColumnName:(NSString*)columnName; 336 | 337 | /** Result set object for column. 338 | 339 | @param columnIdx Zero-based index for column. 340 | 341 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 342 | 343 | @see objectAtIndexedSubscript: 344 | */ 345 | 346 | - (id)objectForColumnIndex:(int)columnIdx; 347 | 348 | /** Result set object for column. 349 | 350 | This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: 351 | 352 | id result = rs[@"employee_name"]; 353 | 354 | This simplified syntax is equivalent to calling: 355 | 356 | id result = [rs objectForKeyedSubscript:@"employee_name"]; 357 | 358 | which is, it turns out, equivalent to calling: 359 | 360 | id result = [rs objectForColumnName:@"employee_name"]; 361 | 362 | @param columnName `NSString` value of the name of the column. 363 | 364 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 365 | */ 366 | 367 | - (id)objectForKeyedSubscript:(NSString *)columnName; 368 | 369 | /** Result set object for column. 370 | 371 | This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: 372 | 373 | id result = rs[0]; 374 | 375 | This simplified syntax is equivalent to calling: 376 | 377 | id result = [rs objectForKeyedSubscript:0]; 378 | 379 | which is, it turns out, equivalent to calling: 380 | 381 | id result = [rs objectForColumnName:0]; 382 | 383 | @param columnIdx Zero-based index for column. 384 | 385 | @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. 386 | */ 387 | 388 | - (id)objectAtIndexedSubscript:(int)columnIdx; 389 | 390 | /** Result set `NSData` value for column. 391 | 392 | @param columnName `NSString` value of the name of the column. 393 | 394 | @return `NSData` value of the result set's column. 395 | 396 | @warning If you are going to use this data after you iterate over the next row, or after you close the 397 | result set, make sure to make a copy of the data first (or just use ``/``) 398 | If you don't, you're going to be in a world of hurt when you try and use the data. 399 | 400 | */ 401 | 402 | - (NSData*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED; 403 | 404 | /** Result set `NSData` value for column. 405 | 406 | @param columnIdx Zero-based index for column. 407 | 408 | @return `NSData` value of the result set's column. 409 | 410 | @warning If you are going to use this data after you iterate over the next row, or after you close the 411 | result set, make sure to make a copy of the data first (or just use ``/``) 412 | If you don't, you're going to be in a world of hurt when you try and use the data. 413 | 414 | */ 415 | 416 | - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; 417 | 418 | /** Is the column `NULL`? 419 | 420 | @param columnIdx Zero-based index for column. 421 | 422 | @return `YES` if column is `NULL`; `NO` if not `NULL`. 423 | */ 424 | 425 | - (BOOL)columnIndexIsNull:(int)columnIdx; 426 | 427 | /** Is the column `NULL`? 428 | 429 | @param columnName `NSString` value of the name of the column. 430 | 431 | @return `YES` if column is `NULL`; `NO` if not `NULL`. 432 | */ 433 | 434 | - (BOOL)columnIsNull:(NSString*)columnName; 435 | 436 | 437 | /** Returns a dictionary of the row results mapped to case sensitive keys of the column names. 438 | 439 | @returns `NSDictionary` of the row results. 440 | 441 | @warning The keys to the dictionary are case sensitive of the column names. 442 | */ 443 | 444 | - (NSDictionary*)resultDictionary; 445 | 446 | /** Returns a dictionary of the row results 447 | 448 | @see resultDictionary 449 | 450 | @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! 451 | */ 452 | 453 | - (NSDictionary*)resultDict __attribute__ ((deprecated)); 454 | 455 | ///----------------------------- 456 | /// @name Key value coding magic 457 | ///----------------------------- 458 | 459 | /** Performs `setValue` to yield support for key value observing. 460 | 461 | @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. 462 | 463 | */ 464 | 465 | - (void)kvcMagic:(id)object; 466 | 467 | 468 | @end 469 | 470 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Classes/fmdb/FMResultSet.m: -------------------------------------------------------------------------------- 1 | #import "FMResultSet.h" 2 | #import "FMDatabase.h" 3 | #import "unistd.h" 4 | 5 | @interface FMDatabase () 6 | - (void)resultSetDidClose:(FMResultSet *)resultSet; 7 | @end 8 | 9 | 10 | @implementation FMResultSet 11 | @synthesize query=_query; 12 | @synthesize statement=_statement; 13 | 14 | + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { 15 | 16 | FMResultSet *rs = [[FMResultSet alloc] init]; 17 | 18 | [rs setStatement:statement]; 19 | [rs setParentDB:aDB]; 20 | 21 | NSParameterAssert(![statement inUse]); 22 | [statement setInUse:YES]; // weak reference 23 | 24 | return FMDBReturnAutoreleased(rs); 25 | } 26 | 27 | - (void)finalize { 28 | [self close]; 29 | [super finalize]; 30 | } 31 | 32 | - (void)dealloc { 33 | [self close]; 34 | 35 | FMDBRelease(_query); 36 | _query = nil; 37 | 38 | FMDBRelease(_columnNameToIndexMap); 39 | _columnNameToIndexMap = nil; 40 | 41 | #if ! __has_feature(objc_arc) 42 | [super dealloc]; 43 | #endif 44 | } 45 | 46 | - (void)close { 47 | [_statement reset]; 48 | FMDBRelease(_statement); 49 | _statement = nil; 50 | 51 | // we don't need this anymore... (i think) 52 | //[_parentDB setInUse:NO]; 53 | [_parentDB resultSetDidClose:self]; 54 | _parentDB = nil; 55 | } 56 | 57 | - (int)columnCount { 58 | return sqlite3_column_count([_statement statement]); 59 | } 60 | 61 | - (NSMutableDictionary *)columnNameToIndexMap { 62 | if (!_columnNameToIndexMap) { 63 | int columnCount = sqlite3_column_count([_statement statement]); 64 | _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; 65 | int columnIdx = 0; 66 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 67 | [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] 68 | forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; 69 | } 70 | } 71 | return _columnNameToIndexMap; 72 | } 73 | 74 | - (void)kvcMagic:(id)object { 75 | 76 | int columnCount = sqlite3_column_count([_statement statement]); 77 | 78 | int columnIdx = 0; 79 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 80 | 81 | const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); 82 | 83 | // check for a null row 84 | if (c) { 85 | NSString *s = [NSString stringWithUTF8String:c]; 86 | 87 | [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; 88 | } 89 | } 90 | } 91 | 92 | #pragma clang diagnostic push 93 | #pragma clang diagnostic ignored "-Wdeprecated-implementations" 94 | 95 | - (NSDictionary*)resultDict { 96 | 97 | NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); 98 | 99 | if (num_cols > 0) { 100 | NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; 101 | 102 | NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; 103 | NSString *columnName = nil; 104 | while ((columnName = [columnNames nextObject])) { 105 | id objectValue = [self objectForColumnName:columnName]; 106 | [dict setObject:objectValue forKey:columnName]; 107 | } 108 | 109 | return FMDBReturnAutoreleased([dict copy]); 110 | } 111 | else { 112 | NSLog(@"Warning: There seem to be no columns in this set."); 113 | } 114 | 115 | return nil; 116 | } 117 | 118 | #pragma clang diagnostic pop 119 | 120 | - (NSDictionary*)resultDictionary { 121 | 122 | NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); 123 | 124 | if (num_cols > 0) { 125 | NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; 126 | 127 | int columnCount = sqlite3_column_count([_statement statement]); 128 | 129 | int columnIdx = 0; 130 | for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { 131 | 132 | NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; 133 | id objectValue = [self objectForColumnIndex:columnIdx]; 134 | [dict setObject:objectValue forKey:columnName]; 135 | } 136 | 137 | return dict; 138 | } 139 | else { 140 | NSLog(@"Warning: There seem to be no columns in this set."); 141 | } 142 | 143 | return nil; 144 | } 145 | 146 | 147 | 148 | 149 | - (BOOL)next { 150 | return [self nextWithError:nil]; 151 | } 152 | 153 | - (BOOL)nextWithError:(NSError **)outErr { 154 | 155 | int rc = sqlite3_step([_statement statement]); 156 | 157 | if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { 158 | NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); 159 | NSLog(@"Database busy"); 160 | if (outErr) { 161 | *outErr = [_parentDB lastError]; 162 | } 163 | } 164 | else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { 165 | // all is well, let's return. 166 | } 167 | else if (SQLITE_ERROR == rc) { 168 | NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 169 | if (outErr) { 170 | *outErr = [_parentDB lastError]; 171 | } 172 | } 173 | else if (SQLITE_MISUSE == rc) { 174 | // uh oh. 175 | NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 176 | if (outErr) { 177 | if (_parentDB) { 178 | *outErr = [_parentDB lastError]; 179 | } 180 | else { 181 | // If 'next' or 'nextWithError' is called after the result set is closed, 182 | // we need to return the appropriate error. 183 | NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; 184 | *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; 185 | } 186 | 187 | } 188 | } 189 | else { 190 | // wtf? 191 | NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); 192 | if (outErr) { 193 | *outErr = [_parentDB lastError]; 194 | } 195 | } 196 | 197 | 198 | if (rc != SQLITE_ROW) { 199 | [self close]; 200 | } 201 | 202 | return (rc == SQLITE_ROW); 203 | } 204 | 205 | - (BOOL)hasAnotherRow { 206 | return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; 207 | } 208 | 209 | - (int)columnIndexForName:(NSString*)columnName { 210 | columnName = [columnName lowercaseString]; 211 | 212 | NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; 213 | 214 | if (n) { 215 | return [n intValue]; 216 | } 217 | 218 | NSLog(@"Warning: I could not find the column named '%@'.", columnName); 219 | 220 | return -1; 221 | } 222 | 223 | 224 | 225 | - (int)intForColumn:(NSString*)columnName { 226 | return [self intForColumnIndex:[self columnIndexForName:columnName]]; 227 | } 228 | 229 | - (int)intForColumnIndex:(int)columnIdx { 230 | return sqlite3_column_int([_statement statement], columnIdx); 231 | } 232 | 233 | - (long)longForColumn:(NSString*)columnName { 234 | return [self longForColumnIndex:[self columnIndexForName:columnName]]; 235 | } 236 | 237 | - (long)longForColumnIndex:(int)columnIdx { 238 | return (long)sqlite3_column_int64([_statement statement], columnIdx); 239 | } 240 | 241 | - (long long int)longLongIntForColumn:(NSString*)columnName { 242 | return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; 243 | } 244 | 245 | - (long long int)longLongIntForColumnIndex:(int)columnIdx { 246 | return sqlite3_column_int64([_statement statement], columnIdx); 247 | } 248 | 249 | - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { 250 | return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; 251 | } 252 | 253 | - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { 254 | return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; 255 | } 256 | 257 | - (BOOL)boolForColumn:(NSString*)columnName { 258 | return [self boolForColumnIndex:[self columnIndexForName:columnName]]; 259 | } 260 | 261 | - (BOOL)boolForColumnIndex:(int)columnIdx { 262 | return ([self intForColumnIndex:columnIdx] != 0); 263 | } 264 | 265 | - (double)doubleForColumn:(NSString*)columnName { 266 | return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; 267 | } 268 | 269 | - (double)doubleForColumnIndex:(int)columnIdx { 270 | return sqlite3_column_double([_statement statement], columnIdx); 271 | } 272 | 273 | - (NSString*)stringForColumnIndex:(int)columnIdx { 274 | 275 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 276 | return nil; 277 | } 278 | 279 | const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); 280 | 281 | if (!c) { 282 | // null row. 283 | return nil; 284 | } 285 | 286 | return [NSString stringWithUTF8String:c]; 287 | } 288 | 289 | - (NSString*)stringForColumn:(NSString*)columnName { 290 | return [self stringForColumnIndex:[self columnIndexForName:columnName]]; 291 | } 292 | 293 | - (NSDate*)dateForColumn:(NSString*)columnName { 294 | return [self dateForColumnIndex:[self columnIndexForName:columnName]]; 295 | } 296 | 297 | - (NSDate*)dateForColumnIndex:(int)columnIdx { 298 | 299 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 300 | return nil; 301 | } 302 | 303 | return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; 304 | } 305 | 306 | 307 | - (NSData*)dataForColumn:(NSString*)columnName { 308 | return [self dataForColumnIndex:[self columnIndexForName:columnName]]; 309 | } 310 | 311 | - (NSData*)dataForColumnIndex:(int)columnIdx { 312 | 313 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 314 | return nil; 315 | } 316 | 317 | const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); 318 | int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); 319 | 320 | if (dataBuffer == NULL) { 321 | return nil; 322 | } 323 | 324 | return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; 325 | } 326 | 327 | 328 | - (NSData*)dataNoCopyForColumn:(NSString*)columnName { 329 | return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; 330 | } 331 | 332 | - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { 333 | 334 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 335 | return nil; 336 | } 337 | 338 | const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); 339 | int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); 340 | 341 | NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; 342 | 343 | return data; 344 | } 345 | 346 | 347 | - (BOOL)columnIndexIsNull:(int)columnIdx { 348 | return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; 349 | } 350 | 351 | - (BOOL)columnIsNull:(NSString*)columnName { 352 | return [self columnIndexIsNull:[self columnIndexForName:columnName]]; 353 | } 354 | 355 | - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { 356 | 357 | if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { 358 | return nil; 359 | } 360 | 361 | return sqlite3_column_text([_statement statement], columnIdx); 362 | } 363 | 364 | - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { 365 | return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; 366 | } 367 | 368 | - (id)objectForColumnIndex:(int)columnIdx { 369 | int columnType = sqlite3_column_type([_statement statement], columnIdx); 370 | 371 | id returnValue = nil; 372 | 373 | if (columnType == SQLITE_INTEGER) { 374 | returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; 375 | } 376 | else if (columnType == SQLITE_FLOAT) { 377 | returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; 378 | } 379 | else if (columnType == SQLITE_BLOB) { 380 | returnValue = [self dataForColumnIndex:columnIdx]; 381 | } 382 | else { 383 | //default to a string for everything else 384 | returnValue = [self stringForColumnIndex:columnIdx]; 385 | } 386 | 387 | if (returnValue == nil) { 388 | returnValue = [NSNull null]; 389 | } 390 | 391 | return returnValue; 392 | } 393 | 394 | - (id)objectForColumnName:(NSString*)columnName { 395 | return [self objectForColumnIndex:[self columnIndexForName:columnName]]; 396 | } 397 | 398 | // returns autoreleased NSString containing the name of the column in the result set 399 | - (NSString*)columnNameForIndex:(int)columnIdx { 400 | return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; 401 | } 402 | 403 | - (void)setParentDB:(FMDatabase *)newDb { 404 | _parentDB = newDb; 405 | } 406 | 407 | - (id)objectAtIndexedSubscript:(int)columnIdx { 408 | return [self objectForColumnIndex:columnIdx]; 409 | } 410 | 411 | - (id)objectForKeyedSubscript:(NSString *)columnName { 412 | return [self objectForColumnName:columnName]; 413 | } 414 | 415 | 416 | @end 417 | -------------------------------------------------------------------------------- /LVDatabaseDemo/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "ipad", 35 | "size" : "29x29", 36 | "scale" : "1x" 37 | }, 38 | { 39 | "idiom" : "ipad", 40 | "size" : "29x29", 41 | "scale" : "2x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "40x40", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "40x40", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "76x76", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "76x76", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } -------------------------------------------------------------------------------- /LVDatabaseDemo/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | com.icfcc.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | UISupportedInterfaceOrientations~ipad 40 | 41 | UIInterfaceOrientationPortrait 42 | UIInterfaceOrientationPortraitUpsideDown 43 | UIInterfaceOrientationLandscapeLeft 44 | UIInterfaceOrientationLandscapeRight 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /LVDatabaseDemo/LVModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // LVModal.h 3 | // LVDatabaseDemo 4 | // 5 | // Created by 刘春牢 on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface LVModel : NSObject 12 | 13 | @property (nonatomic, copy) NSString *name; 14 | 15 | @property (nonatomic, assign) NSInteger age; 16 | 17 | @property (nonatomic, assign) NSInteger ID_No; 18 | 19 | 20 | + (instancetype)modalWith:(NSString *)name age:(NSInteger)age no:(NSInteger)ID_No; 21 | 22 | @end 23 | -------------------------------------------------------------------------------- /LVDatabaseDemo/LVModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // LVModal.m 3 | // LVDatabaseDemo 4 | // 5 | // Created by 刘春牢 on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import "LVModel.h" 10 | 11 | @implementation LVModel 12 | 13 | + (instancetype)modalWith:(NSString *)name age:(NSInteger)age no:(NSInteger)ID_No { 14 | LVModel *model = [[self alloc] init]; 15 | model.name = name; 16 | model.age = age; 17 | model.ID_No = ID_No; 18 | return model; 19 | } 20 | 21 | @end 22 | -------------------------------------------------------------------------------- /LVDatabaseDemo/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // LVDatabaseDemo 4 | // 5 | // Created by PBOC CS on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /LVDatabaseDemo/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // LVDatabaseDemo 4 | // 5 | // Created by PBOC CS on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "LVModel.h" 11 | 12 | #import "LVFmdbTool.h" 13 | 14 | 15 | #define LVSQLITE_NAME @"modals.sqlite" 16 | 17 | 18 | @interface ViewController () 19 | 20 | /** 姓名 */ 21 | @property (weak, nonatomic) IBOutlet UITextField *nameField; 22 | 23 | /** 年龄 */ 24 | @property (weak, nonatomic) IBOutlet UITextField *ageField; 25 | 26 | /** 身份证号码 */ 27 | @property (weak, nonatomic) IBOutlet UITextField *idField; 28 | 29 | /** 插入数据按钮 */ 30 | @property (weak, nonatomic) IBOutlet UIButton *insertBtn; 31 | 32 | /** 查询数据按钮 */ 33 | @property (weak, nonatomic) IBOutlet UIButton *queryBtn; 34 | 35 | /** 删除数据按钮 */ 36 | @property (weak, nonatomic) IBOutlet UIButton *deleteBtn; 37 | 38 | /** 修改数据按钮 */ 39 | @property (weak, nonatomic) IBOutlet UIButton *updateBtn; 40 | 41 | /** 显示数据 */ 42 | @property (weak, nonatomic) IBOutlet UITableView *tableView; 43 | 44 | @property (nonatomic, strong) NSMutableArray *modalsArrM; 45 | 46 | - (IBAction)insertBtnDidClick:(UIButton *)sender; 47 | 48 | - (IBAction)queryBtnDidClick:(UIButton *)sender; 49 | 50 | - (IBAction)deleteBtnDidClick:(UIButton *)sender; 51 | 52 | - (IBAction)updateBtnDidClick:(UIButton *)sender; 53 | 54 | 55 | @property (nonatomic, strong) FMDatabase *fmdb; 56 | 57 | @end 58 | 59 | @implementation ViewController 60 | 61 | - (NSMutableArray *)modalsArrM { 62 | if (!_modalsArrM) { 63 | _modalsArrM = [[NSMutableArray alloc] init]; 64 | } 65 | return _modalsArrM; 66 | } 67 | 68 | 69 | - (void)viewDidLoad { 70 | [super viewDidLoad]; 71 | 72 | // 调整按钮风格 73 | [self setupControl:@[self.insertBtn, self.queryBtn, self.deleteBtn, self.updateBtn]]; 74 | 75 | // 模糊查询 76 | UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)]; 77 | searchBar.delegate = self; 78 | self.tableView.tableHeaderView = searchBar; 79 | } 80 | 81 | #pragma mark - 模糊查询功能演示 82 | - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { 83 | 84 | [self.modalsArrM removeAllObjects]; 85 | 86 | NSString *fuzzyQuerySql = [NSString stringWithFormat:@"SELECT * FROM t_modals WHERE name LIKE '%%%@%%' OR ID_No LIKE '%%%@%%'", searchText, searchText]; 87 | NSArray *modals = [LVFmdbTool queryData:fuzzyQuerySql]; 88 | 89 | [self.modalsArrM addObjectsFromArray:modals]; 90 | 91 | [self.tableView reloadData]; 92 | } 93 | 94 | 95 | 96 | - (void)setupControl:(NSArray *)array { 97 | 98 | [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 99 | UIButton *btn = (UIButton *)obj; 100 | btn.layer.cornerRadius = 7; 101 | }]; 102 | } 103 | 104 | - (IBAction)insertBtnDidClick:(UIButton *)sender { 105 | 106 | if (self.nameField.text.length == 0 || self.ageField.text.length == 0 || self.idField.text.length == 0) return; 107 | 108 | LVModel *model = [LVModel modalWith:self.nameField.text age:self.ageField.text.intValue no:self.idField.text.intValue]; 109 | 110 | BOOL isInsert = [LVFmdbTool insertModel:model]; 111 | 112 | if (isInsert) { 113 | 114 | [self.modalsArrM addObject:model]; 115 | [self.tableView reloadData]; 116 | 117 | } else { 118 | NSLog(@"插入数据失败"); 119 | } 120 | } 121 | 122 | - (IBAction)queryBtnDidClick:(UIButton *)sender { 123 | 124 | [self.modalsArrM removeAllObjects]; 125 | 126 | NSArray *modals = [LVFmdbTool queryData:nil]; 127 | [self.modalsArrM addObjectsFromArray:modals]; 128 | 129 | [self.tableView reloadData]; 130 | 131 | } 132 | - (IBAction)deleteBtnDidClick:(UIButton *)sender { 133 | 134 | NSString *delesql = @"DELETE FROM t_modals WHERE name = 'zhangsan'"; 135 | [LVFmdbTool deleteData:delesql]; 136 | 137 | #warning 删除数据后执行一次查询工作刷新表格 138 | [self queryBtnDidClick:nil]; 139 | } 140 | 141 | - (IBAction)updateBtnDidClick:(UIButton *)sender { 142 | 143 | [LVFmdbTool modifyData:nil]; 144 | #warning 删除数据后执行一次查询工作刷新表格 145 | [self queryBtnDidClick:nil]; 146 | } 147 | 148 | 149 | #pragma mark - UITableViewDataSource 150 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 151 | 152 | return self.modalsArrM.count; 153 | } 154 | 155 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 156 | 157 | static NSString *ID = @"cell"; 158 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; 159 | if (!cell) { 160 | cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID]; 161 | } 162 | 163 | LVModel *model = self.modalsArrM[indexPath.row]; 164 | cell.textLabel.text = model.name; 165 | cell.detailTextLabel.text = [NSString stringWithFormat:@"%zd", model.ID_No]; 166 | return cell; 167 | } 168 | 169 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 170 | return 60; 171 | } 172 | 173 | @end 174 | -------------------------------------------------------------------------------- /LVDatabaseDemo/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // LVDatabaseDemo 4 | // 5 | // Created by PBOC CS on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LVDatabaseDemoTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | com.icfcc.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /LVDatabaseDemoTests/LVDatabaseDemoTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // LVDatabaseDemoTests.m 3 | // LVDatabaseDemoTests 4 | // 5 | // Created by PBOC CS on 15/3/26. 6 | // Copyright (c) 2015年 liuchunlao. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface LVDatabaseDemoTests : XCTestCase 13 | 14 | @end 15 | 16 | @implementation LVDatabaseDemoTests 17 | 18 | - (void)setUp { 19 | [super setUp]; 20 | // Put setup code here. This method is called before the invocation of each test method in the class. 21 | } 22 | 23 | - (void)tearDown { 24 | // Put teardown code here. This method is called after the invocation of each test method in the class. 25 | [super tearDown]; 26 | } 27 | 28 | - (void)testExample { 29 | // This is an example of a functional test case. 30 | XCTAssert(YES, @"Pass"); 31 | } 32 | 33 | - (void)testPerformanceExample { 34 | // This is an example of a performance test case. 35 | [self measureBlock:^{ 36 | // Put the code you want to measure the time of here. 37 | }]; 38 | } 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LVDatabaseDemo 2 | FMDB数据库的使用演示和封装工具类,希望能帮助到用到的朋友,谢谢! 3 | ##使用步骤。。。 4 | 5 | 将FMDB框架及LVFmdbTool拉入项目中,导入头文件,根据需要修改表名《在LVFmdbTool.m》文件中查找models,替换为需要的表明。 6 | ``` 7 | #improt "LVFmdbTool.h" 8 | ``` 9 | 10 | ## 插入数据 11 | ``` 12 | [LVFmdbTool insertModel:model] 13 | ``` 14 | 15 | ## 查询数据 16 | ``` 17 | [LVFmdbTool queryData:nil] 18 | ``` 19 | 20 | ## 删除数据 21 | ``` 22 | [LVFmdbTool deleteData:delesql]; 23 | ``` 24 | 25 | ## 修改数据 26 | ``` 27 | [LVFmdbTool modifyData:nil]; 28 | ``` 29 | 30 | 31 | ## 效果图 32 | ![](https://github.com/liuchunlao/ImageCache/raw/master/gifResource/LVDatabaseDemo.gif) 33 | 34 | ## 期待 35 | * 如果在使用过程中遇到BUG,希望你能Issues我,谢谢! --------------------------------------------------------------------------------