The source code is as follows, only one class file
DBHelper.h//// Created by Jason_Msbaby on 15/10/15.// copyright ? 2015 Zhang Jie . all rights reserved.///** * Simple encapsulation of the use of SQLite not added to transactions and other complex features execution based on incoming SQL statements using singleton mode automatically create tables based on model objects support for NSInter NSString float data types only Default increase id auto-increment primary key default to single database mode default database name databse.sqlite */#import <Foundation/Foundation.h> @interface DBHelper : NSObject/** * Creating singleton objects * * @return Return to this class instance */+ (instancetype) defaultmanger;/** * Create datasheet * * @param sql sql statement * * @return return Create a successful identity */-(BOOL) Creattabel: (nsstring*) sql;/** * using entity types for automatic table * * @param tableName Table name * @param modelType Entity types Properties for automatic retrieval of entities * * @return return bool */-( BOOL) Createtabel: (nsstring*) Tablename modeltype: (Class) modeltype;/** * additions and deletions statements general execution method * * @param sql Incoming SQL statements * * @return return bool value */-(BOOL) Execute: (nsstring*) sql;/** * Execute query * * @param sql incoming SQL statement * * @return return Array < dictionary > dictionary keys are the same as database field names */-(nsmutablearray*) executeQuery :(nsstring*) sql;/** * insert an Entity object into a table * * @param model entity Objects * @param tableName table names * * @return Returns the BOOL value */-(BOOL) Insertmodel: (ID) Model tablename: (nsstring *) TableName; @end
DBHelper.m// douBan//// Created by Jason_Msbaby on 15/10/15.// copyright ? 2015 Zhang Jie all rights reserved.//#import <objc/runtime.h> #import "DBHelper.h" #import <sqlite3.h> #define cachepath [ Nssearchpathfordirectoriesindomains (Nscachesdirectory, nsuserdomainmask, yes) objectAtIndex:0]# define databasename @ "Database.sqlite" @implementation dbhelperstatic dbhelper * dbhelper;static sqlite3 *sql3;//********************************************* specific implementation of partial ***** + (Instancetype) defaultmanger{ if (dbhelper == nil) { dbhelper = [DBHelper New]; } return dbhelper;} -(BOOL) Creattabel: (nsstring *) SQL{&NBSP;&NBSP;&NBSP;&NBSp;return [self execute:sql];} -(BOOL) Createtabel: (nsstring *) Tablename modeltype: (Class) modeltype{ nsmutablestring *sql = [nsmutablestring stringwithformat:@ "CREATE TABLE IF not exists '%@ ' (' id ' integer primary key autoincrement, ",tableName]; nsarray *names =[nsarray arraywitharray:[self allpropertynameinclass: modeltype]]; for (nsdictionary *dic in names) { nsstring *name = dic[@ "Name"]; nsstring *type = dic[@ "Type"]; [sql appendstring:[nsstring stringwithformat:@ "'%@ ' %@ ,",name,type]]; } nsstring *realsql = [sql substringtoindex:sql.length-1]; realsql = [realsql stringbyappendingstring:@ ");"]; nslog (@ "%@", realsql); return [self execute:realsql];} -(BOOL) Execute: (nsstring *) sql{ [self open]; int Res = sqlite3_exec (Sql3, sql. Utf8string, null, null, null); [self close]; return !res;} -(nsmutablearray *) ExecuteQuery: (nsstring *) sql{ [self open]; sqlite3_stmt *stmt = nil; nsmutablearray *arr = [nsmutablearray array]; int res = sqlite3_prepare (sql3 , sql. Utf8string, -1, &stmt, null); if (Res == SQLITE_OK) { while (Sqlite3_step (stmt) == sqlite_row) { int count = sqlite3_column_count (stmt); nsmutabledictionary *dic = [ nsmutabledictionary dictionary]; for (int i = 0; i < count; i++) { const char *columname = sqlite3_column_name (stmt, i); const char *value = (const char*) Sqlite3_column_text ( Stmt, i); if (value!=null) { NSString *columValue =[NSString stringWithUTF8String:value]; [dic setobject:columvalue forkey:[nsstring stringwithutf8string:columname]]; }else{ [dic setobject: @ "" forKey:[NSString stringWithUTF8String:columName]]; } } [arr addobject :d Ic]; &nbsP; } sqlite3_finalize (stmt); [self close]; return arr; }else{ return nil; } return nil;} -(BOOL) Insertmodel: (ID) Model tablename: (nsstring *) tablename{ nsdictionary *dic = [self dictionaryfrommodel:model]; nsmutablestring * keys = [nsmutablestring string]; nsmutablestring *values = [NSMutableString string]; for (int i = 0; i < dic.count; i++) { nsstring *key = dic.allkeys[i]; nsstring *value = dic.allvalues[i]; [keys appendformat:@ "%@,",key]; [values appendformat:@ "'%@ ',", value]; } nsstring *sql = [nsstring stringwithformat:@ "insert into %@ (%@) values (%@)", tablename,[keys substringtoindex:keys.length -1],[values substringtoindex:values.length - 1]]; nslog (@ "%@", SQL); return ! [Self execute:sql];} This kind of auxiliary function ***************************************//-( BOOL) open{ nsstring *filename = [cachepath Stringbyappendingpathcomponent:databasename]; nslog (@ "path=%@", FileName); return !sqlite3_open (Filename.utf8striNG,&NBSP;&SQL3);} -(BOOL) close{ return !sqlite3_close (SQL3);} Dictionary and object conversion function//object to Dictionary-(nsdictionary*) Dictionaryfrommodel: (ID) model{ nsmutabledictionary *dic = [nsmutabledictionary dictionary]; class modelclass = object_getclass (model); unsigned int count = 0; objc_property_t *pros = class_copypropertylist (ModelClass, &count); for (int i = 0; i < count; i++) { objc_property_t pro = pros[i]; nsstring *name = [nsstring stringwithformat:@ "%s", property_getname (PRO)] ; id value = [model valueforkey:name]; if (Value !=nil) { [dic setObject:value forKey:name]; } } free (Pros); return dic;} Attribute dynamic parsing section ***************************************//// The runtime helper function parses the attribute characteristics of the class, such as behavior//Get Properties of eigenvalues-(nsstring*) Attrvaluewithname: (nsstring*) Name inproperty: (objc_property_t ) pro{ unsigned int count = 0; objc_property_ Attribute_t *attrs = property_copyattributelist (Pro, &count); for (int i = 0; i < count; i++) { objc_property_attribute_t attr = attrs[i]; if (strcmp (attr.name, name. utf8string) == 0) { return [nsstring stringwithutf8string:attr.value]; } } free (attrs); return nil;} Gets the value of the property-(ID) Valueofproperty: (objc_property_t) Pro cls: (Class) Cls{ ivar ivar = class_getinstancevariable (cls, [self attrvaluewithname:@ "V" InProperty:pro]. utf8string); return object_getivar (Cls, ivar);} Gets all the property names and types of the class-(nsarray *) Allpropertynameinclass: (Class) cls{ nsmutablearray *arr = [nsmutablearray array]; unsigned int count; objc_property_t *pros = class_copypropertylist (cls, &count); for (int i = 0; i < count; i++) { nsstring *name =[nsstring stringwithformat:@ "%s", Property_getName (Pros[i]); nsstring *type = [self attrvaluewithname:@ "T" inproperty:pros[i]]; //type conversion if ([type isequaltostring:@ "Q"]| | [type isequaltostring:@ "I"]) { type = @ "INTEGER"; }else if ([type isequaltostring:@ "F"] | | [type isequaltostring:@ "D"]) { type = @ "REAL"; }else{ type = @ "TEXT"; } nsdictionary *dic = @{@ "name": name,@ "type": type}; [arr addObject:dic]; } free (pros); return arr;} @end
Simple encapsulation Sqlite3 implementation of entity objects related to relational database "IOS"