首页 > 开发 > 综合 > 正文

iOS

2024-07-21 02:48:23
字体:
来源:转载
供稿:网友
iOS - SQLite Database 操作数据库iOS - SQLite Database 操作数据库

Sqlite 能被用在ios上做数据处理用,只要你懂得一点sql 就很容易使用sqlite

1:创建一个简单的View based application2:现在你的项目文件,选择targets 并从库中选择libsqlite3.dylib添加到框架中

3:我们创建一个新的文件 File->New->File->选择Objective C class 并点击next

4:类名称取名为DBManager 子类为NSObject

5:选择创建

6:更新DBManager.h文件

123456789101112131415#import <Foundation/Foundation.h>#import <sqlite3.h>@interfaceDBManager :NSObject{NSString*databasePath;}+(DBManager*)getSharedInstance;-(BOOL)createDB;-(BOOL) saveData:(NSString*)registerNumber name:(NSString*)namedepartment:(NSString*)department year:(NSString*)year;-(NSArray*) findByRegisterNumber:(NSString*)registerNumber;@end

7:更新DBManager.m文件

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112#import "DBManager.h"staticDBManager *sharedInstance =nil;staticsqlite3 *database =nil;staticsqlite3_stmt *statement =nil;@implementationDBManager+(DBManager*)getSharedInstance{if(!sharedInstance) {sharedInstance = [[superallocWithZone:NULL]init];[sharedInstance createDB];}returnsharedInstance;}-(BOOL)createDB{NSString*docsDir;NSArray*dirPaths;// Get the documents directorydirPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);docsDir = dirPaths[0];// Build the path to the database filedatabasePath = [[NSStringalloc] initWithString:[docsDir stringByAppendingPathComponent: @"student.db"]];BOOLisSuccess =YES;NSFileManager*filemgr = [NSFileManagerdefaultManager];if([filemgr fileExistsAtPath: databasePath ] ==NO){constchar*dbpath = [databasePath UTF8String];if(sqlite3_open(dbpath, &database) == SQLITE_OK){char*errMsg;constchar*sql_stmt ="create tableifnot exists studentsDetail (regno integerPRimary key, name text, department text, year text)";if(sqlite3_exec(database, sql_stmt,NULL,NULL, &errMsg)!= SQLITE_OK){isSuccess =NO;NSLog(@"Failed to create table");}sqlite3_close(database);returnisSuccess;}else{isSuccess =NO;<
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表