当C++遇到iOS应用开发:SQLITE篇

移动开发 iOS
在XCODE 开发时,可以很方便的引入SQLITE库来开发基于支持本地数据库的应用。但网上查到的大部分内容都只是介绍一个简单的示例而已。众所周知,微软的 ADO.NET很好很强大,且已发展多年,其使用方式也很灵活多样。

本系列的主要方向是引导iOS开发者特别是之前用C#和C++的朋友,可以一步步搭建属于拥有.net风格的基本类库,并快速进行iOS应用的开发。不过前提是读者和开发者有一定的C++开发经验,以免遇到一些诡异问题时,能够快速找出解决方案。

在XCODE 开发时,可以很方便的引入SQLITE库来开发基于支持本地数据库的应用。但网上查到的大部分内容都只是介绍一个简单的示例而已。众所周知,微软的 ADO.NET很好很强大,且已发展多年,其使用方式也很灵活多样。如果将其哪怕部分实现方式“移植”到IOS上,那即使是.NET新手也可以很快适应。 在网上基于C++实现连接SQLITE的示例代码多如牛毛,但封装的却不甚理想。***笔者在CODEPROJECT上终于挖出一个老项目,里面基本上定义 了一些实现方式和框架且实现得短小精悍,且利于扩充,所以我就在其基础上,逐步加入了一些新的功能。所以就有了今天的内容。

在ADO.NET中定义了一些基本的数据库访问组件,比如DataSet,DataTable,DataRow,以及事务等。

下面就来看一下用C++实现这些对象的方式。

首先是DataSet:

  1. typedef class CppSQLite3DB 
  2. public: 
  3.     CppSQLite3DB(); 
  4.     CppSQLite3DB(const char* szFile); 
  5.     virtual ~CppSQLite3DB(); 
  6.     void open(const char* szFile); 
  7.     void close(); 
  8.     bool tableExists(const char* szTable); 
  9.     int execDML(const char* szSQL); 
  10.     //该方法为execNoQuery的封装 
  11.     int execNoQuery(const char* szSQL); 
  12.     CppSQLite3Query execQuery(const char* szSQL); 
  13.     int execScalar(const char* szSQL); 
  14.     CppSQLite3Table getTable(const char* szSQL); 
  15.     CppSQLite3Statement compileStatement(const char* szSQL); 
  16.     sqlite_int64 lastRowId(); 
  17.     void interrupt() { sqlite3_interrupt(mpDB); } 
  18.     void setBusyTimeout(int nMillisecs); 
  19.     static const char* Version() { return SQLITE_VERSION; } 
  20. public: 
  21.     CppSQLite3DB(const CppSQLite3DB& db); 
  22.     CppSQLite3DB& operator=(const CppSQLite3DB& db); 
  23.     sqlite3_stmt* compile(const char* szSQL); 
  24.     void checkDB(); 
  25.     sqlite3* mpDB; 
  26.     int mnBusyTimeoutMs; 
  27. } DB; 

需要注意的是这里使用的某些方法名称是基于笔者以前开发DISCUT!NT时使用的DBHelper.cs类时使用的名称,这也是让团队里的老成员能很快适应这个框架的一个原因。

上面基本上就是对数据库及数据表(DataTable)进行基本操作的封装。

而数据表及数据行的定义如下:

  1. typedef class CppSQLite3Table 
  2. public
  3.     CppSQLite3Table(); 
  4.     CppSQLite3Table(const CppSQLite3Table& rTable); 
  5.     CppSQLite3Table(char** paszResults, int nRows, int nCols); 
  6.     virtual ~CppSQLite3Table(); 
  7.     CppSQLite3Table& operator=(const CppSQLite3Table& rTable); 
  8.     int fieldsCount(); 
  9.     int rowsCount(); 
  10.     const char* fieldName(int nCol); 
  11.     const char* fieldValue(int nField); 
  12.     const char* operator[](int nField); 
  13.     const char* fieldValue(const char* szField); 
  14.     const char* operator[](const char* szField); 
  15.     int getIntField(int nField, int nNullValue=0); 
  16.     int getIntField(const char* szField, int nNullValue=0); 
  17.     double getFloatField(int nField, double fNullValue=0.0); 
  18.     double getFloatField(const char* szField, double fNullValue=0.0); 
  19.     const char* getStringField(int nField, const char* szNullValue=""); 
  20.     const char* getStringField(const char* szField, const char* szNullValue=""); 
  21.     bool fieldIsNull(int nField); 
  22.     bool fieldIsNull(const char* szField); 
  23.     void setRow(int nRow); 
  24.     const CppSQLite3TableRow getRow(int nRow); 
  25.     void finalize(); 
  26. private
  27.     void checkResults(); 
  28.     int mnCols; 
  29.     int mnRows; 
  30.     int mnCurrentRow; 
  31.     char** mpaszResults; 
  32. } Table; 
  33. typedef class CppSQLite3TableRow 
  34. private
  35.     Table& inTable; 
  36. public
  37.     const char* operator[](int nField); 
  38.     const char* operator[](const char* szField); 
  39.     CppSQLite3TableRow( Table& table):inTable(table){} 
  40.     virtual ~CppSQLite3TableRow(void
  41.     {}; 
  42. } Row; 

注意:关于Row的实现是老代码中所没有的,因为要考虑到尽量逼成ADO.NET的对象结构,所以这里加入了进来;

有了上面的对象支持,接下来就可以写一个封装类DBHelper.h来实现常用数据访问操作了,如下:

  1. #ifndef DBHelper_h 
  2. #define DBHelper_h 
  3. #include "SQLiteHelper.h" 
  4. //#include <ctime> 
  5. #include <iostream> 
  6. using namespace std; 
  7. using namespace SQLiteWrapper; 
  8. namespace SQLiteWrapper { 
  9. class DBHelper 
  10. private
  11.     DBHelper() 
  12.     {} 
  13.     virtual ~DBHelper(void
  14.     {} 
  15. public
  16.     static DB db; 
  17.     static DB loadDb() 
  18.     { 
  19.         DB database; 
  20.         { 
  21.             NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
  22.             NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory/*NSCachesDirectory*/, NSUserDomainMask, YES); 
  23.             NSString *path = [arr objectAtIndex:0]; 
  24.             path = [path stringByAppendingPathComponent:@"MySqlLitePath"]; 
  25.             // create directory for db if it not exists 
  26.             NSFileManager *fileManager = [[NSFileManager alloc] init]; 
  27.             BOOL isDirectory = NO; 
  28.             BOOL exists = [fileManager  fileExistsAtPath:path isDirectory:&isDirectory]; 
  29.             if (!exists) { 
  30.                 [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil]; 
  31.                 if (![fileManager fileExistsAtPath:path]) { 
  32.                     [NSException raise:@"FailedToCreateDirectory" format:@"Failed to create a directory for the db at '%@'",path]; 
  33.                 } 
  34.             } 
  35.             [fileManager release]; 
  36.             // create db object 
  37.             NSString *dbfilePath = [path stringByAppendingPathComponent:@"Blogs"]; 
  38.             std::string dbpathstr =[dbfilePath UTF8String]; 
  39.             const char *dbpath = dbpathstr.c_str();//"/Users/MySqlLitePath/Blogs"; 
  40.             database.open(dbpath); 
  41.             [pool release]; 
  42.         } 
  43.         return database; 
  44.     } 
  45.     static bool tableExists(const char* szTable) 
  46.     { 
  47.        return db.tableExists(szTable); 
  48.     } 
  49.        static int execNoQuery(const char* szSQL) 
  50.     } 
  51.         return db.execDML(szSQL); 
  52.     } 
  53.     static int execNoQuery(const NSString* szSQL) 
  54.     { 
  55.         return db.execDML([szSQL UTF8String].c_str()); 
  56.     } 
  57.     static Query execQuery(const char* szSQL) 
  58.     { 
  59.         return db.execQuery(szSQL); 
  60.     } 
  61.     static Query execQuery(const NSString* szSQL) 
  62.     { 
  63.         return db.execQuery([szSQL UTF8String].c_str()); 
  64.     } 
  65.     static Query execScalar(const char* szSQL) 
  66.     { 
  67.         return db.execQuery(szSQL); 
  68.     } 
  69.     static int execScalar(const NSString* szSQL) 
  70.     { 
  71.         return db.execScalar([szSQL UTF8String].c_str()); 
  72.     } 
  73.     static Table getTable(const char* szSQL) 
  74.     { 
  75.         return db.getTable(szSQL); 
  76.     } 
  77.     static Table getTable(const NSString* szSQL) 
  78.     { 
  79.         return db.getTable([szSQL UTF8String].c_str()); 
  80.     } 
  81.     static Statement compileStatement(const char* szSQL) 
  82.     { 
  83.         return db.compileStatement(szSQL); 
  84.     } 
  85.     static Statement compileStatement(const NSString* szSQL) 
  86.     { 
  87.         return db.compileStatement([szSQL UTF8String].c_str()); 
  88.     } 
  89.     static sqlite_int64 lastRowId() 
  90.     { 
  91.         return db.lastRowId(); 
  92.     } 
  93.     static void setBusyTimeout(int nMillisecs) 
  94.     { 
  95.         db.setBusyTimeout(nMillisecs); 
  96.     } 
  97. }; 

DB DBHelper::db = DBHelper::loadDb(); //在全局区进行对象初始化操作。

这里要注意的一点就是,在其静态方法loadDb()中,要使用Object-C中的NSAutoreleasePool对象来“框住”数据库的加载逻辑代码,否则会在下面这一样产生内存泄露:

  1. NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory/*NSCachesDirectory*/, NSUserDomainMask, YES); 

下面我们来看如何使用它,上DEMO。

判断当前数据库中是否存在某个TABLE,如存在则删除,之后创建新表:

  1. if(DBHelper::tableExists("emp")){ 
  2.     DBHelper::execNoQuery("drop table emp;"); 
  3. DBHelper::execNoQuery("create table emp(empno int, empname char(20));");   

接着向新表中接入数据并返回插入成功的条数,如下:

  1. int nRows = DBHelper::execNoQuery("insert into emp values (7, 'David Beckham');"); 
  2.    cout << nRows << " rows inserted" << endl; 

然后进行UPDATE,DELETE操作并返回操作的记录条数:

  1. nRows = DBHelper::execNoQuery("update emp set empname = 'Christiano Ronaldo' where empno = 7;"); 
  2. cout << nRows << " rows updated" << endl; 
  3. nRows = DBHelper::execNoQuery("delete from emp where empno = 7;"); 
  4. cout << nRows << " rows deleted" << endl; 

基于事务属性进行批量操作,以提升性能:

  1. int nRowsToCreate(50000); 
  2.    cout << endl << "Transaction test, creating " << nRowsToCreate; 
  3.    cout << " rows please wait..." << endl; 
  4.    DBHelper::execNoQuery("begin transaction;"); 
  5.    for (int i = 0; i < nRowsToCreate; i++) 
  6.    { 
  7.        char buf[128]; 
  8.        sprintf(buf, "insert into emp values (%d, 'Empname%06d');", i, i); 
  9.        DBHelper::execNoQuery(buf); 
  10.    } 
  11.    DBHelper::execNoQuery("commit transaction;"); 

进行select count操作:

  1. cout << DBHelper::execScalar("select count(*) from emp;") << " rows in emp table in "

使用Buffer进行SQL语句构造:

  1. Buffer bufSQL; 
  2.    bufSQL.format("insert into emp (empname) values (%Q);""He's bad"); 
  3.    cout << (const char*)bufSQL << endl; 
  4.    DBHelper::execNoQuery(bufSQL); 
  5.    DBHelper::execNoQuery(bufSQL); 
  6.    bufSQL.format("insert into emp (empname) values (%Q);", NULL); 
  7.    cout << (const char*)bufSQL << endl; 
  8.    DBHelper::execNoQuery(bufSQL); 

遍历数据集方式1:

  1. Query q = DBHelper::execQuery("select * from emp order by 1;"); 
  2.        for (int fld = 0; fld < q.fieldsCount(); fld++){ 
  3.        cout << q.fieldName(fld) << "(" << q.fieldDeclType(fld) << ")|"
  4.    } 
  5.    cout << endl; 
  6.        while (!q.eof()){ 
  7.        cout << q.fieldValue(0) << "|" ; 
  8.        cout << q.fieldValue(1) << "|" << endl;             
  9.        cout << q.fieldValue("empno") << "||" ; 
  10.        cout << q.fieldValue("empname") << "||" << endl; 
  11.        //或使用[]索引,效果同q.fieldValue 
  12.        cout << q[0] << "|" ; 
  13.        cout << q[1] << "|" << endl; 
  14.        cout << q["empno"] << "||" ; 
  15.        cout << q["empname"] << "||" << endl; 
  16.        q.nextRow(); 
  17.    } 

遍历数据集方式2:

  1. Table t = DBHelper::getTable("select * from emp order by 1;"); 
  2.           for (int fld = 0; fld < t.fieldsCount(); fld++){ 
  3.        cout << t.fieldName(fld) << "|"
  4.    } 
  5.    for (int row = 0; row < t.rowsCount(); row++){   
  6.        Row r= t.getRow(row); 
  7.        cout << r["empno"] << " " << r["empname"] << "|"
  8.        cout << endl; 
  9.    } 

预编译Statements测试(使用场景不多):

  1. cout << endl << "Transaction test, creating " << nRowsToCreate; 
  2.    cout << " rows please wait..." << endl; 
  3.    DBHelper::execNoQuery("drop table emp;"); 
  4.    DBHelper::execNoQuery("create table emp(empno int, empname char(20));"); 
  5.    DBHelper::execNoQuery("begin transaction;"); 
  6.    Statement stmt = DBHelper::compileStatement("insert into emp values (?, ?);"); 
  7.    for (int i = 0; i < nRowsToCreate; i++){ 
  8.        char buf[16]; 
  9.        sprintf(buf, "EmpName%06d", i); 
  10.        stmt.bind(1, i); 
  11.        stmt.bind(2, buf); 
  12.        stmt.execDML(); 
  13.        stmt.reset(); 
  14.    } 
  15.    DBHelper::execNoQuery("commit transaction;"); 

***我们只要找一个相应的.m文件改成.mm后缀,将上面测试语句执行一下,就可以了。

责任编辑:闫佳明 来源: cocoachina
相关推荐

2013-05-02 11:13:05

C++遇到iOS应用开字符串处理

2014-04-14 10:21:15

开发运维DevOps

2011-08-22 16:26:25

IOS开发Sqlite数据库

2015-07-10 15:31:42

ITIoT物联网

2012-09-05 09:04:36

C++SQLite

2012-07-16 09:05:43

云计算法律

2011-09-02 19:12:59

IOS应用Sqlite数据库

2015-09-18 15:22:56

DCIMITSM

2013-01-06 09:52:43

SQLite

2013-04-09 16:04:06

iOS开发SQLite知识总结

2018-05-17 11:23:06

智能化

2015-05-06 15:27:11

腾讯云移动应用

2021-09-23 14:41:58

鸿蒙HarmonyOS应用

2010-09-01 15:42:39

DHCP SnoopiARP

2011-03-01 10:58:00

2013-04-01 10:49:51

iOS开发sqlite数据库

2018-03-27 09:10:54

区块链

2011-07-28 15:11:23

iOS Objective-

2014-06-04 13:19:29

C++ndk安卓开发

2010-01-28 10:33:10

C++开发程序
点赞
收藏

51CTO技术栈公众号