2010-06-25 65 views
4

我做這個代碼在DBSQLite計數(*)如何得到結果?

int rows = 0; 
if (sqlite3_open([[SqliteManager getDBPath] UTF8String], &database) == SQLITE_OK) { 
    const char *sql = "select count(*) from artheca"; 
    sqlite3_stmt *countstmt; 

    if(sqlite3_prepare_v2(database, sql, -1, &countstmt, NULL) == SQLITE_OK) {    
     NSLog(@"inside"); 
     rows = sqlite3_column_int(countstmt, 0); 
    } 
} 
else 
    sqlite3_close(database); 
return rows; 

數列的數字,但結果始終是0

所以,我不知道如果rows = sqlite3_column_int(countstmt, 0);是可以得到正確的語句行數...是否正確?

+0

看起來像一個錯誤的錯誤 - 列從0開始,而不是1. – Piskvor 2010-06-25 09:24:26

回答

5

編輯:要執行你需要call all these 6 functions in order SQL語句:

sqlite3_open()  Open the database 
sqlite3_prepare()  Create the SQL statement 
sqlite3_step()  Execute the statement 
sqlite3_column()  Fetch the result 
sqlite3_finalize() Destroy the statement 
sqlite3_close()  Close the database 

你缺少sqlite3_stepsqlite3_finalize步驟。

順便說一句,你可以使用sqlite3_get_table()sqlite3_exec()這些簡單的查詢。


http://www.sqlite.org/c3ref/column_blob.html

結果集的最左邊的列的索引爲0

因此,你應該使用

rows = sqlite3_column_int(countstmt, 0); 
+0

你是對的,但在函數中使用0仍然返回相同的結果。 。所以我修理我的文章,因爲這不是我認爲的觀點! – nox 2010-06-25 09:32:26

+0

+1提醒步驟!謝謝! – NightFury 2013-05-16 08:30:59

4

你之前錯過sqlite3_step(countstmt); rows = sqlite3_column_int(countstmt, 0);爲了執行查詢