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> @interface DBManager : NSObject {
NSString *databasePath; } +(DBManager*)getSharedInstance; -( BOOL )createDB; -( BOOL ) saveData:( NSString *)registerNumber name:( NSString *)name
department:( NSString *)department year:( NSString *)year; -( NSArray *) findByRegisterNumber:( NSString *)registerNumber; @end |
7:更新DBManager.m文件
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 | #import "DBManager.h" static DBManager *sharedInstance = nil ; static sqlite3 *database = nil ; static sqlite3_stmt *statement = nil ; @implementation DBManager +(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[ super allocWithZone: NULL ]init];
[sharedInstance createDB];
}
return sharedInstance; } -( BOOL )createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains
( NSDocumentDirectory , NSUserDomainMask , YES );
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[ NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: @ "student.db" ]];
BOOL isSuccess = YES ;
NSFileManager *filemgr = [ NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO )
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"create table if not exists studentsDetail (regno integer
PRimary 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);
return isSuccess;
}
else {
isSuccess = NO ; < |