2013-02-12 39 views
0

代碼只需要讓來電者知道path是否在表中。 下面的C++代碼可以正確使用select count(*)sqlite3_get_table,但只有很短的時間,然後死亡。 sqlite3_get_table顯然存在問題。 有一個非常類似的問題here,但我不知道如何將這個答案應用於我的問題。 我已經閱讀了sqlite文檔並通過了sqlite教程。 我已經使用sqlite3_exec來初始化數據庫並插入新記錄,但再次看不到如何編寫一個健壯的C++方法,只需返回一個布爾,如果它發現或沒有找到表中的匹配。正如我所說,下面的代碼有效,但不超過幾百次。這不應該是數據庫最簡單的事情之一嗎?是否有任何簡單的例子說明如何做到這一點或建議解決這個問題的最佳方法?擺脫sqlite3_get_table的如何在sql表中找到str

bool ifFound(string path) { 
    if (turn_off) return false; 
    char **result; 
    int nrow = 0; // Number of result rows 
    int ncol = 0; // Number of result columns 
    char * zErrMsg = 0; // Error message 
    if (SQLITE_OK != sqlite3_open(database_path.c_str(), &db)) { 
     coutError(__FILE__, __LINE__, "Can't open database " + database_path); 
     return false; 
    } 
    int count = 0; 
    string sqlCommand = "select count(*) from my_table where path='"+path+"'"; 
    if (SQLITE_OK == 
     sqlite3_get_table(db, sqlCommand.c_str(),&result,&nrow,&ncol,&zErrMsg)) 
     count = atoi(result[ncol]); 
    else coutError(__FILE__, __LINE__, sqlCommand + " " + zErrMsg); 
    sqlite3_free_table(result); 
    sqlite3_close(db); 
    return (count != 0); 
} 
+0

你對「死」有什麼意思? – 2013-02-12 16:24:52

+0

@CL。 'die'我的意思是這個過程(embedded-linux)剛剛消失,不知道是誰殺了它或者爲什麼。但是當ifFound被stubbed時,代碼運行沒問題,這使得它相當確定問題出在sqlite3_get_table上。 – jacknad 2013-02-12 17:05:58

+0

這個函數沒有什麼明顯的錯誤。你不能用調試器或桌面運行你的程序嗎? – 2013-02-12 18:59:01

回答

1

一種方式是使用sqlite3_exec,一個回調來處理查詢結果,而一個全局變量來保存數來取代它。

static int pathFound = 0; 
int sqlCallback(void *p, int argc, char **argv, char **azColName) { 
    pathFound = atoi(argv[0]); 
    return 0; 
} 
void checkPath(string path) { 
    string sqlCommand = "select count(*) from m_table where path='"+path+"'"; 
    rc = sqlite3_exec(db, sqlCommand.c_str(), sqlCallback, 0, &zErrMsg); 
    if (SQLITE_OK != rc) { 
     coutError(__FILE__, __LINE__, sqlCommand + "\n" + zErrMsg); 
     sqlite3_free(zErrMsg); 
    } 
    sqlite3_close(db); 
    if (0 == pathFound) doInsert(path); 
}