當(dāng)C++遇到iOS應(yīng)用開發(fā):SQLITE篇
本系列的主要方向是引導(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:
- typedef class CppSQLite3DB
- {
- public:
- CppSQLite3DB();
- CppSQLite3DB(const char* szFile);
- virtual ~CppSQLite3DB();
- void open(const char* szFile);
- void close();
- bool tableExists(const char* szTable);
- int execDML(const char* szSQL);
- //該方法為execNoQuery的封裝
- int execNoQuery(const char* szSQL);
- CppSQLite3Query execQuery(const char* szSQL);
- int execScalar(const char* szSQL);
- CppSQLite3Table getTable(const char* szSQL);
- CppSQLite3Statement compileStatement(const char* szSQL);
- sqlite_int64 lastRowId();
- void interrupt() { sqlite3_interrupt(mpDB); }
- void setBusyTimeout(int nMillisecs);
- static const char* Version() { return SQLITE_VERSION; }
- public:
- CppSQLite3DB(const CppSQLite3DB& db);
- CppSQLite3DB& operator=(const CppSQLite3DB& db);
- sqlite3_stmt* compile(const char* szSQL);
- void checkDB();
- sqlite3* mpDB;
- int mnBusyTimeoutMs;
- } 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ù)行的定義如下:
- typedef class CppSQLite3Table
- {
- public:
- CppSQLite3Table();
- CppSQLite3Table(const CppSQLite3Table& rTable);
- CppSQLite3Table(char** paszResults, int nRows, int nCols);
- virtual ~CppSQLite3Table();
- CppSQLite3Table& operator=(const CppSQLite3Table& rTable);
- int fieldsCount();
- int rowsCount();
- const char* fieldName(int nCol);
- const char* fieldValue(int nField);
- const char* operator[](int nField);
- const char* fieldValue(const char* szField);
- const char* operator[](const char* szField);
- int getIntField(int nField, int nNullValue=0);
- int getIntField(const char* szField, int nNullValue=0);
- double getFloatField(int nField, double fNullValue=0.0);
- double getFloatField(const char* szField, double fNullValue=0.0);
- const char* getStringField(int nField, const char* szNullValue="");
- const char* getStringField(const char* szField, const char* szNullValue="");
- bool fieldIsNull(int nField);
- bool fieldIsNull(const char* szField);
- void setRow(int nRow);
- const CppSQLite3TableRow getRow(int nRow);
- void finalize();
- private:
- void checkResults();
- int mnCols;
- int mnRows;
- int mnCurrentRow;
- char** mpaszResults;
- } Table;
- typedef class CppSQLite3TableRow
- {
- private:
- Table& inTable;
- public:
- const char* operator[](int nField);
- const char* operator[](const char* szField);
- CppSQLite3TableRow( Table& table):inTable(table){}
- virtual ~CppSQLite3TableRow(void)
- {};
- } Row;
注意:關(guān)于Row的實(shí)現(xiàn)是老代碼中所沒有的,因?yàn)橐紤]到盡量逼成ADO.NET的對象結(jié)構(gòu),所以這里加入了進(jìn)來;
有了上面的對象支持,接下來就可以寫一個(gè)封裝類DBHelper.h來實(shí)現(xiàn)常用數(shù)據(jù)訪問操作了,如下:
- #ifndef DBHelper_h
- #define DBHelper_h
- #include "SQLiteHelper.h"
- //#include <ctime>
- #include <iostream>
- using namespace std;
- using namespace SQLiteWrapper;
- namespace SQLiteWrapper {
- class DBHelper
- {
- private:
- DBHelper()
- {}
- virtual ~DBHelper(void)
- {}
- public:
- static DB db;
- static DB loadDb()
- {
- DB database;
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory/*NSCachesDirectory*/, NSUserDomainMask, YES);
- NSString *path = [arr objectAtIndex:0];
- path = [path stringByAppendingPathComponent:@"MySqlLitePath"];
- // create directory for db if it not exists
- NSFileManager *fileManager = [[NSFileManager alloc] init];
- BOOL isDirectory = NO;
- BOOL exists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
- if (!exists) {
- [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
- if (![fileManager fileExistsAtPath:path]) {
- [NSException raise:@"FailedToCreateDirectory" format:@"Failed to create a directory for the db at '%@'",path];
- }
- }
- [fileManager release];
- // create db object
- NSString *dbfilePath = [path stringByAppendingPathComponent:@"Blogs"];
- std::string dbpathstr =[dbfilePath UTF8String];
- const char *dbpath = dbpathstr.c_str();//"/Users/MySqlLitePath/Blogs";
- database.open(dbpath);
- [pool release];
- }
- return database;
- }
- static bool tableExists(const char* szTable)
- {
- return db.tableExists(szTable);
- }
- static int execNoQuery(const char* szSQL)
- }
- return db.execDML(szSQL);
- }
- static int execNoQuery(const NSString* szSQL)
- {
- return db.execDML([szSQL UTF8String].c_str());
- }
- static Query execQuery(const char* szSQL)
- {
- return db.execQuery(szSQL);
- }
- static Query execQuery(const NSString* szSQL)
- {
- return db.execQuery([szSQL UTF8String].c_str());
- }
- static Query execScalar(const char* szSQL)
- {
- return db.execQuery(szSQL);
- }
- static int execScalar(const NSString* szSQL)
- {
- return db.execScalar([szSQL UTF8String].c_str());
- }
- static Table getTable(const char* szSQL)
- {
- return db.getTable(szSQL);
- }
- static Table getTable(const NSString* szSQL)
- {
- return db.getTable([szSQL UTF8String].c_str());
- }
- static Statement compileStatement(const char* szSQL)
- {
- return db.compileStatement(szSQL);
- }
- static Statement compileStatement(const NSString* szSQL)
- {
- return db.compileStatement([szSQL UTF8String].c_str());
- }
- static sqlite_int64 lastRowId()
- {
- return db.lastRowId();
- }
- static void setBusyTimeout(int nMillisecs)
- {
- db.setBusyTimeout(nMillisecs);
- }
- };
- }
DB DBHelper::db = DBHelper::loadDb(); //在全局區(qū)進(jìn)行對象初始化操作。
這里要注意的一點(diǎn)就是,在其靜態(tài)方法loadDb()中,要使用Object-C中的NSAutoreleasePool對象來“框住”數(shù)據(jù)庫的加載邏輯代碼,否則會在下面這一樣產(chǎn)生內(nèi)存泄露:
- NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory/*NSCachesDirectory*/, NSUserDomainMask, YES);
下面我們來看如何使用它,上DEMO。
判斷當(dāng)前數(shù)據(jù)庫中是否存在某個(gè)TABLE,如存在則刪除,之后創(chuàng)建新表:
- if(DBHelper::tableExists("emp")){
- DBHelper::execNoQuery("drop table emp;");
- }
- DBHelper::execNoQuery("create table emp(empno int, empname char(20));");
接著向新表中接入數(shù)據(jù)并返回插入成功的條數(shù),如下:
- int nRows = DBHelper::execNoQuery("insert into emp values (7, 'David Beckham');");
- cout << nRows << " rows inserted" << endl;
然后進(jìn)行UPDATE,DELETE操作并返回操作的記錄條數(shù):
- nRows = DBHelper::execNoQuery("update emp set empname = 'Christiano Ronaldo' where empno = 7;");
- cout << nRows << " rows updated" << endl;
- nRows = DBHelper::execNoQuery("delete from emp where empno = 7;");
- cout << nRows << " rows deleted" << endl;
基于事務(wù)屬性進(jìn)行批量操作,以提升性能:
- int nRowsToCreate(50000);
- cout << endl << "Transaction test, creating " << nRowsToCreate;
- cout << " rows please wait..." << endl;
- DBHelper::execNoQuery("begin transaction;");
- for (int i = 0; i < nRowsToCreate; i++)
- {
- char buf[128];
- sprintf(buf, "insert into emp values (%d, 'Empname%06d');", i, i);
- DBHelper::execNoQuery(buf);
- }
- DBHelper::execNoQuery("commit transaction;");
進(jìn)行select count操作:
- cout << DBHelper::execScalar("select count(*) from emp;") << " rows in emp table in ";
使用Buffer進(jìn)行SQL語句構(gòu)造:
- Buffer bufSQL;
- bufSQL.format("insert into emp (empname) values (%Q);", "He's bad");
- cout << (const char*)bufSQL << endl;
- DBHelper::execNoQuery(bufSQL);
- DBHelper::execNoQuery(bufSQL);
- bufSQL.format("insert into emp (empname) values (%Q);", NULL);
- cout << (const char*)bufSQL << endl;
- DBHelper::execNoQuery(bufSQL);
遍歷數(shù)據(jù)集方式1:
- Query q = DBHelper::execQuery("select * from emp order by 1;");
- for (int fld = 0; fld < q.fieldsCount(); fld++){
- cout << q.fieldName(fld) << "(" << q.fieldDeclType(fld) << ")|";
- }
- cout << endl;
- while (!q.eof()){
- cout << q.fieldValue(0) << "|" ;
- cout << q.fieldValue(1) << "|" << endl;
- cout << q.fieldValue("empno") << "||" ;
- cout << q.fieldValue("empname") << "||" << endl;
- //或使用[]索引,效果同q.fieldValue
- cout << q[0] << "|" ;
- cout << q[1] << "|" << endl;
- cout << q["empno"] << "||" ;
- cout << q["empname"] << "||" << endl;
- q.nextRow();
- }
遍歷數(shù)據(jù)集方式2:
- Table t = DBHelper::getTable("select * from emp order by 1;");
- for (int fld = 0; fld < t.fieldsCount(); fld++){
- cout << t.fieldName(fld) << "|";
- }
- for (int row = 0; row < t.rowsCount(); row++){
- Row r= t.getRow(row);
- cout << r["empno"] << " " << r["empname"] << "|";
- cout << endl;
- }
預(yù)編譯Statements測試(使用場景不多):
- cout << endl << "Transaction test, creating " << nRowsToCreate;
- cout << " rows please wait..." << endl;
- DBHelper::execNoQuery("drop table emp;");
- DBHelper::execNoQuery("create table emp(empno int, empname char(20));");
- DBHelper::execNoQuery("begin transaction;");
- Statement stmt = DBHelper::compileStatement("insert into emp values (?, ?);");
- for (int i = 0; i < nRowsToCreate; i++){
- char buf[16];
- sprintf(buf, "EmpName%06d", i);
- stmt.bind(1, i);
- stmt.bind(2, buf);
- stmt.execDML();
- stmt.reset();
- }
- DBHelper::execNoQuery("commit transaction;");
***我們只要找一個(gè)相應(yīng)的.m文件改成.mm后綴,將上面測試語句執(zhí)行一下,就可以了。