0

我是 sqlite 数据库的新手。我有一个名为 FIREWALL_TABLE_LIST 的表,我想从中提取 CAN_MESSAGE_ID 值并存储在我的 c 程序中声明的变量 message_ID 中。有什么帮助或建议吗?

#ifdef TEST_VECTORS
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
 int i;
for(i=0; i<argc; i++){
  printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
 }

int main(int argc, char* argv[])
{
    /* INITIALIZATION */
    int message_ID = 0;

    /* INITIALIZATION for database*/
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    char *sql;
    const char* data = "Callback function called";

    /* Open database */
    rc = sqlite3_open("rt.db", &db);
    if( rc ){
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        exit(0);
    }else{
        fprintf(stderr, "\nOpened database successfully\n\n");
    }   

    /* Create SQL statement */
    sql = "SELECT * from FIREWALL_TABLE_LIST WHERE DATE_TIME = (SELECT MAX(DATE_TIME) FROM FIREWALL_TABLE_LIST)";
    /* Execute SQL statement */
    rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout, "Operation done successfully\n\n");
    }

    sqlite3_close(db);
    fprintf(stderr, "Closed database successfully\n\n");
    return 0;
}
#endif /* TEST_VECTORS */
4

1 回答 1

0

您不应该使用SELECT *,因为列的顺序和数量会随着数据库模式的每次更改而变化。只需使用SELECT CAN_MESSAGE_ID ....

sqlite3_exec回调接收一堆字符串,因此您必须将值转换回数字:

message_ID = atoi(argv[0]);
于 2013-08-14T09:44:03.213 回答