文章撰寫日期︰2013/03/19 13:46 cocos2dx使用版本︰v 2.0.4
cocosBuilder使用版本︰v 2.0 alpha 1
一、問題
在Xcode中,使用sqlite3 *pDB = NULL;//資料庫指針
string szResPath(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath("millionschool.sqlite"));
sqlite3_open(szResPath.c_str(), &pDB);
就能順利將Resources資料夾下的millionschool.sqlite打開並使用。但是,
Android卻無法這樣子打開,
返回了錯誤碼14。
二、解決方法
經爬文後發現,sqlite3 *pDB = NULL;//資料庫指針CCFileUtils::sharedFileUtils()->fullPathFromRelativePath("millionschool.sqlite"));
這個取到的路徑在Android下會被壓縮,無法正常存取。
解決方法只有將sqlite檔案複製至可存取的Android資料夾方可使用。
CCFileUtils::sharedFileUtils()->getWriteablePath();此方法在Android底下會取到本機裡data\data\package_name\這個目錄,
於是我們將assets底下的sqlite複製到這邊來。
sqlite3 *pDB = NULL;//資料庫指針
char * errMsg = NULL;//錯誤訊息
std::string sqlstr;//SQL指令
int result;//sqlite3_exec返回值
string szResPath(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath("millionschool.sqlite"));//IOS可以這樣用,但Android卻不行
//取得Android可以使用的data\data\package_name資料夾
string dbPath = CCFileUtils::sharedFileUtils()->getWriteablePath();
dbPath.append("millionschool.sqlite");
//將資料寫入串流
unsigned long tmpSize;
unsigned char* dbData = CCFileUtils::sharedFileUtils()->getFileData(szResPath.c_str(), "rb", &tmpSize);
FILE *fp = fopen(dbPath.c_str(), "wb");
fwrite(dbData, tmpSize, 1, fp);
fclose(fp);
//將資料庫打開來看看
result = sqlite3_open(dbPath.c_str(), &pDB);
if( result != SQLITE_OK ){
CCLog( "打開資料庫失敗,錯誤碼:%d ,錯誤原因:%s\n" , result, errMsg );
}else{
CCLog( "打開資料庫成功!" );
}
成功了!
讀到資料庫了!
沒有留言 :
張貼留言