ios-数据库-sqlite-数据库得封装(自己写得,有很多不严谨)最后还有一个单例得实现
libsqlite3.0.dylib//使用的时候要先导入这个库
staic UserDB* instance//UserDB是一个管理数据库的类 +(void) shareInstance{ if(instance==nil) { instance=[[[self class]alloc]init]; } return instance; }
// // UserDB.m // sqllitedemo // // Created by liyang on 14-4-26. // Copyright (c) 2014年 liyang. All rights reserved. // #import "UserDB.h" @implementation UserDB -(void)createTable:(NSString *)sql{ sqlite3 *sqllite=nil; NSString *sqllitepath=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/data.sqlite"]; int result=sqlite3_open([sqllitepath UTF8String], &sqllite); if (result!=SQLITE_OK) { NSLog(@"打开数据库失败"); return; } char *error=NULL; int createtableresult= sqlite3_exec(sqllite, [sql UTF8String], NULL, NULL, &error); if (createtableresult!=SQLITE_OK) { NSLog(@"创建表失败"); sqlite3_close(sqllite); return; } sqlite3_close(sqllite); } -(void)insertData:(NSString *)sql{ sqlite3 *sqllite=nil; sqlite3_stmt *stmt=nil; NSString *sqllitepath=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/data.sqlite"]; int result=sqlite3_open([sqllitepath UTF8String], &sqllite); if (result!=SQLITE_OK) { NSLog(@"打开数据库失败"); return; } int stmtresult=sqlite3_prepare_v2(sqllite, [sql UTF8String], -1, &stmt, NULL); if (stmtresult!=SQLITE_OK) { NSLog(@"编译失败"); sqlite3_close(sqllite); return; } NSString *username=@"liyang11"; NSString *password=@"123456"; NSString *email=@"liyang20098@163.com"; sqlite3_bind_text(stmt, 1, [username UTF8String], -1, NULL); sqlite3_bind_text(stmt, 2, [password UTF8String], -1, NULL); sqlite3_bind_text(stmt, 3, [email UTF8String], -1, NULL); int stepresult=sqlite3_step(stmt); NSLog(@"%d",stepresult); if (stepresult==SQLITE_ERROR||stepresult==SQLITE_MISUSE||SQLITE_CONSTRAINT==stepresult) { NSLog(@"执行失败"); sqlite3_finalize(stmt); sqlite3_close(sqllite); return; } sqlite3_finalize(stmt); sqlite3_close(sqllite); NSLog(@"插入语句成功"); } -(void)selectData:(NSString *)sql{ sqlite3 *sqllite=nil; sqlite3_stmt *stmt=nil; NSString *sqllitepath=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/data.sqlite"]; int result=sqlite3_open([sqllitepath UTF8String], &sqllite); if (result!=SQLITE_OK) { NSLog(@"打开数据库失败"); return; } int stmtresult=sqlite3_prepare_v2(sqllite, [sql UTF8String], -1, &stmt, NULL); if (stmtresult!=SQLITE_OK) { NSLog(@"编译失败"); sqlite3_close(sqllite); return; } NSString *password=@"123456"; sqlite3_bind_text(stmt, 1, [password UTF8String], -1, NULL); int stepresult=sqlite3_step(stmt); if (stepresult==SQLITE_ERROR||stepresult==SQLITE_MISUSE||SQLITE_CONSTRAINT==stepresult) { NSLog(@"执行失败"); sqlite3_finalize(stmt); sqlite3_close(sqllite); return; } while (stepresult==SQLITE_ROW) { char * username=(char *)sqlite3_column_text(stmt, 0);//注意这是从0开始,上面绑定参数的是从1开始 char * password=(char *)sqlite3_column_text(stmt, 1); char * email=(char *)sqlite3_column_text(stmt, 2); NSString *username_new= [NSString stringWithCString:username encoding:NSUTF8StringEncoding]; NSString *password_new= [NSString stringWithCString:password encoding:NSUTF8StringEncoding]; NSString *email_new= [NSString stringWithCString:email encoding:NSUTF8StringEncoding]; NSLog(@"username:%@------password:%@------email:%@",username_new,password_new,email_new); stepresult=sqlite3_step(stmt); } sqlite3_finalize(stmt); sqlite3_close(sqllite); NSLog(@"查询句成功"); } @end
//下面是一个工具类
// // DataBaseModel.h // Track-tripStrategy // // Created by ncg ncg-2 on 11-11-5. // Copyright 2011 www.iphonetrain.com 无限互联3G学院. All rights reserved. // #import <Foundation/Foundation.h> #import <sqlite3.h> @interface BaseDB : NSObject { sqlite3 *database; } //创建表 -(void)createTable:(NSString *)sql; /** * 接口描述:查询数据 * 参数: sql:sql语句 * columns: 查询的字段数量 * 返回值:[["字段值1","字段值2"],.....]; */ - (NSMutableArray *)selectData:(NSString *)sql columns:(int)col; /** * 接口描述:增,删,改数据库 * 参数: sql:SQL语句 paramarray: 参数 * 返回值:是否执行成功 * */ - (BOOL)dealData:(NSString *)sql paramarray:(NSArray *)param; /** * 接口描述:保存带"图片/文件"的字段 */ - (BOOL)saveimage:(NSString *)sql paramarray:(NSMutableArray *)param; /** * 接口描述:查询图片数据 */ - (UIImage *)selectData:(NSString *)sql; /** * 接口描述:查询某张表中数据的数量 */ - (NSUInteger) selectCount:(NSString *)sql; - (NSMutableArray *)selectFullData:(NSString *)sql columns:(int)col ; + (void)createAllTabel; @end
// // DataBaseModel.m // Track-tripStrategy // // Created by ncg ncg-2 on 11-11-5. // Copyright 2011 www.iphonetrain.com 无限互联3G学院 All rights reserved. // #import "BaseDB.h" #import "UserDB.h" @implementation BaseDB #define kFilename @"data.sqlite" - (NSString *)dataFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:kFilename]; } //创建表 -(void)createTable:(NSString *)sql { //打开数据库 if (sqlite3_open([[self dataFilePath] UTF8String], &database)!= SQLITE_OK) { sqlite3_close(database); NSAssert(0, @"Failed to open database"); } char *errorMsg; //创建一个表 if (sqlite3_exec (database, [sql UTF8String],NULL, NULL, &errorMsg) != SQLITE_OK) { sqlite3_close(database); NSAssert1(0, @"Error creating table: %s", errorMsg); } } #pragma mark 查询数据库 /************ sql:sql语句 col:sql语句需要操作的表的所有字段数 ***********/ - (NSMutableArray *)selectData:(NSString *)sql columns:(int)col { //打开数据库 if (sqlite3_open([[self dataFilePath] UTF8String], &database)!= SQLITE_OK) { sqlite3_close(database); NSAssert(0, @"Failed to open database"); } NSMutableArray *returndata = [[[NSMutableArray alloc] init] autorelease];//所有记录 sqlite3_stmt *statement = nil; if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { NSMutableArray *row;//一条记录 row = [[NSMutableArray alloc] init]; for(int i=0; i<col; i++) { char* contentchar = (char*)sqlite3_column_text(statement, i); if (contentchar) { [row addObject:[NSString stringWithFormat:@"%@",[NSString stringWithUTF8String:contentchar]]]; } } [returndata addObject:row]; [row release]; } }else { NSLog(@"Error: failed to prepare"); return NO; } sqlite3_finalize(statement); return returndata; } #pragma mark 查询数据库 /************ sql:sql语句 col:sql语句需要操作的表的所有字段数 ***********/ - (NSMutableArray *)selectFullData:(NSString *)sql columns:(int)col { //打开数据库 if (sqlite3_open([[self dataFilePath] UTF8String], &database)!= SQLITE_OK) { sqlite3_close(database); NSAssert(0, @"Failed to open database"); } NSMutableArray *returndata = [[[NSMutableArray alloc] init] autorelease];//所有记录 sqlite3_stmt *statement = nil; if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { NSMutableArray *row;//一条记录 row = [[NSMutableArray alloc] init]; for(int i=0; i<col; i++) { char* contentchar = (char*)sqlite3_column_text(statement, i); if (contentchar) { [row addObject:[NSString stringWithFormat:@"%@",[NSString stringWithUTF8String:contentchar]]]; } else { [row addObject:@""]; } } [returndata addObject:row]; [row release]; } }else { NSLog(@"Error: failed to prepare"); return NO; } sqlite3_finalize(statement); NSLog(@"%@",returndata); return returndata; } /************ sql:sql语句 ***********/ - (UIImage *)selectData:(NSString *)sql { UIImage *returnimg = [[UIImage alloc] init]; if (sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) { sqlite3_stmt *statement = nil; if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { int bytes = sqlite3_column_bytes(statement, 0); const void *value = sqlite3_column_blob(statement, 0); if( value != NULL && bytes != 0 ){ NSData *data = [NSData dataWithBytes:value length:bytes]; returnimg=[UIImage imageWithData:data]; } else{ NSLog(@"img is null"); } } }else { NSLog(@"Error: failed to prepare"); return NO; } return returnimg; sqlite3_finalize(statement); } else { sqlite3_close(database); NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database)); }//end if sqlite3_close(database); return [returnimg autorelease]; } #pragma mark 增,删,改数据库 /************ sql:sql语句 param:sql语句中?对应的值组成的数组 ***********/ - (BOOL)dealData:(NSString *)sql paramarray:(NSArray *)param { // sql = @"INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) VALUES (?, ?);"; // sql = @"INSERT INTO TravelPointTable ( trackId , latitude , longitude) VALUES ( ?,?,?);"; // param = [NSArray arrayWithObjects:@"11111",@"22222",@"3333",nil]; if (sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) { sqlite3_stmt *statement = nil; int success = sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL); if (success != SQLITE_OK) { NSLog(@"Error: failed to prepare"); return NO; } //绑定参数 for (int i=0; i<[param count]; i++) { NSString *temp = [param objectAtIndex:i]; sqlite3_bind_text(statement, i+1, [temp UTF8String], -1, SQLITE_TRANSIENT); } success = sqlite3_step(statement); sqlite3_finalize(statement); if (success == SQLITE_ERROR) { NSLog(@"Error: failed to insert into the database"); return NO; } } sqlite3_close(database); NSLog(@"处理成功!"); return TRUE; } #pragma 查询某个东西的合计 - (NSUInteger) selectCount:(NSString *)sql { NSUInteger total = 0; // const char *sql = "SELECT COUNT(*) AS amount FROM xxx"; if (sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) { sqlite3_stmt *statement = nil; if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) != SQLITE_OK) { NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database)); } if (sqlite3_step(statement) == SQLITE_ROW) { total = sqlite3_column_int(statement, 0); } sqlite3_finalize(statement); } return total; } #pragma mark 向数据库保存图片 /************ sql:sql语句 param: ***********/ - (BOOL)saveimage:(NSString *)sql paramarray:(NSMutableArray *)param { if (sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) { sqlite3_stmt *statement = nil; int success =sqlite3_prepare(database,[sql UTF8String],-1,&statement,0); // int success = sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL); if (success != SQLITE_OK) { NSLog(@"Error: failed to prepare"); return NO; } //绑定参数 for (int i=0; i<[param count]; i++) { if (i==2) { NSData *imgdata = [param objectAtIndex:2]; sqlite3_bind_blob(statement, 3, [imgdata bytes], [imgdata length], NULL);//如果是nsdata型 } else { NSString *temp = [param objectAtIndex:i]; sqlite3_bind_text(statement, i+1, [temp UTF8String], -1, SQLITE_TRANSIENT); } } success = sqlite3_step(statement); sqlite3_finalize(statement); if (success == SQLITE_ERROR) { NSLog(@"Error: failed to insert into the database"); return NO; } } NSLog(@"处理成功!"); return TRUE; } + (void)createAllTabel { [[UserDB sharedUserDB] createTable]; } @end
1.这里只记录一些学习笔记
2.这里只记录一些学习心得,如果心得方向有错,请留言
2.这里只记录一些日记(只为提升英语,暂时有点忙,等转行了开始写)