自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

當(dāng)C++遇到iOS應(yīng)用開發(fā):SQLITE篇

移動開發(fā) iOS
在XCODE 開發(fā)時(shí),可以很方便的引入SQLITE庫來開發(fā)基于支持本地?cái)?shù)據(jù)庫的應(yīng)用。但網(wǎng)上查到的大部分內(nèi)容都只是介紹一個(gè)簡單的示例而已。眾所周知,微軟的 ADO.NET很好很強(qiáng)大,且已發(fā)展多年,其使用方式也很靈活多樣。

本系列的主要方向是引導(dǎo)iOS開發(fā)者特別是之前用C#和C++的朋友,可以一步步搭建屬于擁有.net風(fēng)格的基本類庫,并快速進(jìn)行iOS應(yīng)用的開發(fā)。不過前提是讀者和開發(fā)者有一定的C++開發(fā)經(jīng)驗(yàn),以免遇到一些詭異問題時(shí),能夠快速找出解決方案。

在XCODE 開發(fā)時(shí),可以很方便的引入SQLITE庫來開發(fā)基于支持本地?cái)?shù)據(jù)庫的應(yīng)用。但網(wǎng)上查到的大部分內(nèi)容都只是介紹一個(gè)簡單的示例而已。眾所周知,微軟的 ADO.NET很好很強(qiáng)大,且已發(fā)展多年,其使用方式也很靈活多樣。如果將其哪怕部分實(shí)現(xiàn)方式“移植”到IOS上,那即使是.NET新手也可以很快適應(yīng)。 在網(wǎng)上基于C++實(shí)現(xiàn)連接SQLITE的示例代碼多如牛毛,但封裝的卻不甚理想。***筆者在CODEPROJECT上終于挖出一個(gè)老項(xiàng)目,里面基本上定義 了一些實(shí)現(xiàn)方式和框架且實(shí)現(xiàn)得短小精悍,且利于擴(kuò)充,所以我就在其基礎(chǔ)上,逐步加入了一些新的功能。所以就有了今天的內(nèi)容。

在ADO.NET中定義了一些基本的數(shù)據(jù)庫訪問組件,比如DataSet,DataTable,DataRow,以及事務(wù)等。

下面就來看一下用C++實(shí)現(xiàn)這些對象的方式。

首先是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; 

需要注意的是這里使用的某些方法名稱是基于筆者以前開發(fā)DISCUT!NT時(shí)使用的DBHelper.cs類時(shí)使用的名稱,這也是讓團(tuán)隊(duì)里的老成員能很快適應(yīng)這個(gè)框架的一個(gè)原因。

上面基本上就是對數(shù)據(jù)庫及數(shù)據(jù)表(DataTable)進(jìn)行基本操作的封裝。

而數(shù)據(jù)表及數(shù)據(jù)行的定義如下:

  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; 

注意:關(guān)于Row的實(shí)現(xiàn)是老代碼中所沒有的,因?yàn)橐紤]到盡量逼成ADO.NET的對象結(jié)構(gòu),所以這里加入了進(jìn)來;

有了上面的對象支持,接下來就可以寫一個(gè)封裝類DBHelper.h來實(shí)現(xiàn)常用數(shù)據(jù)訪問操作了,如下:

  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(); //在全局區(qū)進(jìn)行對象初始化操作。

這里要注意的一點(diǎn)就是,在其靜態(tài)方法loadDb()中,要使用Object-C中的NSAutoreleasePool對象來“框住”數(shù)據(jù)庫的加載邏輯代碼,否則會在下面這一樣產(chǎn)生內(nèi)存泄露:

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

下面我們來看如何使用它,上DEMO。

判斷當(dāng)前數(shù)據(jù)庫中是否存在某個(gè)TABLE,如存在則刪除,之后創(chuàng)建新表:

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

接著向新表中接入數(shù)據(jù)并返回插入成功的條數(shù),如下:

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

然后進(jìn)行UPDATE,DELETE操作并返回操作的記錄條數(shù):

  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; 

基于事務(wù)屬性進(jìn)行批量操作,以提升性能:

  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;"); 

進(jìn)行select count操作:

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

使用Buffer進(jìn)行SQL語句構(gòu)造:

  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); 

遍歷數(shù)據(jù)集方式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.    } 

遍歷數(shù)據(jù)集方式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.    } 

預(yù)編譯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;"); 

***我們只要找一個(gè)相應(yīng)的.m文件改成.mm后綴,將上面測試語句執(zhí)行一下,就可以了。

責(zé)任編輯:閆佳明 來源: cocoachina
相關(guān)推薦

2013-05-02 11:13:05

C++遇到iOS應(yīng)用開字符串處理

2014-04-14 10:21:15

開發(fā)運(yùn)維DevOps

2011-08-22 16:26:25

IOS開發(fā)Sqlite數(shù)據(jù)庫

2015-07-10 15:31:42

ITIoT物聯(lián)網(wǎng)

2012-09-05 09:04:36

C++SQLite

2015-09-18 15:22:56

DCIMITSM

2012-07-16 09:05:43

云計(jì)算法律

2018-05-17 11:23:06

智能化

2011-09-02 19:12:59

IOS應(yīng)用Sqlite數(shù)據(jù)庫

2013-01-06 09:52:43

SQLite

2013-04-09 16:04:06

iOS開發(fā)SQLite知識總結(jié)

2015-05-06 15:27:11

騰訊云移動應(yīng)用

2011-03-01 10:58:00

2021-09-23 14:41:58

鴻蒙HarmonyOS應(yīng)用

2010-09-01 15:42:39

DHCP SnoopiARP

2010-01-28 10:33:10

C++開發(fā)程序

2018-03-27 09:10:54

區(qū)塊鏈

2014-06-04 13:19:29

C++ndk安卓開發(fā)

2013-04-01 10:49:51

iOS開發(fā)sqlite數(shù)據(jù)庫

2011-07-28 15:11:23

iOS Objective-
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號