Ads 468x60px

##EasyReadMore##

05 8月, 2016

query sql sqlite3_get_table 程式停住

原因是在狂 query sql 資料時
4到5小時程式會停住但不會死
也沒有錯誤訊息
網路有人指出 sqlite3_get_table 不建議被使用

The problems with sqlite3_get_table are that all values are converted to strings, and that memory must be allocated for all result records.

You are supposed to use the sqlite3_prepare_v2/sqlite3_step/sqlite3_column_xxx/sqlite3_finalize functions.

所以就來改用 sqlite3_prepare_v2/sqlite3_step/sqlite3_column_xxx/sqlite3_finalize 吧

範例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <sqlite3.h>
#include <cstdlib>
#include <assert.h>

using namespace std;

int main(int argc, char** argv)
{
 sqlite3 *conn;
 sqlite3_stmt *statement; // SQL Statement Object
 int ret = 0;
 int cols;

 // This routine opens a connection to an SQLite database file
 //  and returns a database connection object.
 ret = sqlite3_open_v2("hello.db", &conn, SQLITE_OPEN_READONLY, NULL);
 if (ret) {
  cout << "can not open database\n";
  exit(0);
 }

 ret = sqlite3_prepare_v2(conn, "select * from hello", -1, &statement, NULL);
 if (ret != SQLITE_OK) {
  cout << "We did not get any data\n";
  exit(0);
 }

 sqlite3_stmt *statement;
 int rc = 0,colNum,i;
 if ((rc = sqlite3_prepare_v2(db, sql, -1, &statement, 0)) == SQLITE_OK) {
  colNum = sqlite3_column_count(statement);
  if (colNum)
  {
   for (i = 0; i < colNum; i++)
    printf("%s\t", sqlite3_column_name(statement, i));
   printf("\n");
   while ((rc = sqlite3_step(statement)) == SQLITE_ROW){
    for (i = 0; i < colNum; i++){
     //if(1)printf("%s\t", sqlite3_column_text(statement, i));
     switch (sqlite3_column_type(statement, i)) {
       case SQLITE_INTEGER:
         cout << " " << sqlite3_column_int(statement, i) << " ";
         break;
       case SQLITE_FLOAT:
         cout << " " << sqlite3_column_double(statement, i) << " ";
         break;
       case SQLITE_TEXT:
         cout << " " << sqlite3_column_text(statement, i) << " ";
         break;
       case SQLITE_NULL:
         cout << " " << "NULL" << " ";
         break;
     }
    }
    printf("\n");
   }
   printf("\n");
  }
  sqlite3_finalize(statement);
 }
 else
  rc = SQLITE_ERROR;
  }

  sqlite3_finalize(statement);
  sqlite3_close(conn);

  return 0;
}

參考:
c++ - Why the interface sqlite3_get_table in SQLite C Interface is not recommended - Stack Overflow - http://goo.gl/QJwks9

Nano雞排: 八月 2012 - http://goo.gl/WCDnej

SQLite Example - http://goo.gl/f46OZE

0 意見:

張貼留言

 
Blogger Templates