2

For example my inquiry(question?) in SQL is:

 SELECT * from COMPANY where imie="John",surname="Wattson",age=31;

I use sqlite3_exec where one of the arguments is callback. I don't know if this record is in my table, and would like to know it using sqlite_exec.

What should I do? Sorry for my English. :(

Mittal Patel
  • 2,732
  • 14
  • 23

2 Answers2

2

If you just want to see if a record exists in the table, then you could do it with sqlite3_exec() using a callback function like this:

int myCallback(void *pUser, int argc, char **colData, char **colNames) {
  int *flag = (int*)pUser;
  *flag = 1;
  return 1;
}

This works because if there are no records matching the query, then the callback function is not called. By returning 1 instead of 0, we are telling SQLite that we don't want any more rows from the query results.

Then, in the function where you are making the db query:

std::string sql = "SELECT * FROM COMPANY WHERE imie='John' AND surname='Wattson' AND age=31;";
char *pSql = sql.c_str(); // char*'s are better for talking to SQLite, and prior to C++14,
                          // a std::string is not guaranteed to be sequential in memory,
                          // so 'sql[0]' may not work right

char *pError = NULL;
int fHasResult = 0;

// db is an already-opened sqlite3*
int result = sqlite3_exec(db, pSql, myCallback, &fHasResult, &pError);
if (result) {
  cout<<"Error was: "<<pError;
  free(pError);
}
if (fHasResult) {
  cout<<"The row exists in the database.";
}
else {
  cout<<"The row does not exist in the database.";
}
Mark Benningfield
  • 2,800
  • 9
  • 31
  • 31
1

You could use EXISTS, your query should then look something like this;
SELECT EXISTS (SELECT * FROM COMPANY WHERE imie="John" AND surname="Wattson" AND age=31);
For another example you could take a look at this;
Valid query to check if row exists in SQLite3

Tess E. Duursma
  • 186
  • 1
  • 8
  • Thanks it's helpful, but now how get this value to the variable? – Artur Szczypta Mar 01 '18 at 13:53
  • Oh, you're using c++, so I probably won't be of any help, but the best suggestion I can give you is to fetch the first row in the resultset, which will then contain the result, although I do not know how you could implement that in c++. (Good luck!) – Tess E. Duursma Mar 01 '18 at 14:00