sqlite3 get data from table c

Solutions on MaxInterview for sqlite3 get data from table c by the best coders in the world

showing results for - "sqlite3 get data from table c"
Augustin
20 Feb 2017
1#include <stdio.h>
2#include <string>
3using std::string;
4#include <sstream>
5using std::stringstream;
6
7#include "sqlite3.h"
8
9bool find_employee(int _id)
10{
11    bool found = false;
12    sqlite3* db;
13    sqlite3_stmt* stmt;
14    stringstream ss;
15
16    // create sql statement string
17    // if _id is not 0, search for id, otherwise print all IDs
18    // this can also be achieved with the default sqlite3_bind* utilities
19    if(_id) { ss << "select * from employees where id = " << _id << ";"; }
20    else { ss << "select * from employees;"; }
21    string sql(ss.str());
22
23    //the resulting sql statement
24    printf("sql: %s\n", sql.c_str());
25
26    //get link to database object
27    if(sqlite3_open("data/test.db", &db) != SQLITE_OK) {
28        printf("ERROR: can't open database: %s\n", sqlite3_errmsg(db));
29        sqlite3_close(db);
30        return found;
31    }
32
33    // compile sql statement to binary
34    if(sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
35        printf("ERROR: while compiling sql: %s\n", sqlite3_errmsg(db));
36        sqlite3_close(db);
37        sqlite3_finalize(stmt);
38        return found;
39    }
40
41    // execute sql statement, and while there are rows returned, print ID
42    int ret_code = 0;
43    while((ret_code = sqlite3_step(stmt)) == SQLITE_ROW) {
44        printf("TEST: ID = %d\n", sqlite3_column_int(stmt, 0));
45        found = true;
46    }
47    if(ret_code != SQLITE_DONE) {
48        //this error handling could be done better, but it works
49        printf("ERROR: while performing sql: %s\n", sqlite3_errmsg(db));
50        printf("ret_code = %d\n", ret_code);
51    }
52
53    printf("entry %s\n", found ? "found" : "not found");
54
55    //release resources
56    sqlite3_finalize(stmt);
57    sqlite3_close(db);
58
59    return found;
60}