如何知道sqlite中的函数'回调'是否返回了什么?

问题描述 投票:2回答:2

例如,我在SQL中的查询(问题?)是:

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

我使用sqlite3_exec,其中一个参数是callback。我不知道这个记录是否在我的表中,并且想要使用sqlite_exec知道它。

我该怎么办?对不起我的英语不好。 :(

c++ sql sqlite
2个回答
0
投票

如果您只是想查看表中是否存在记录,那么您可以使用sqlite3_exec()使用这样的回调函数来执行此操作:

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

这是有效的,因为如果没有与查询匹配的记录,则不会调用回调函数。通过返回1而不是0,我们告诉SQLite我们不希望查询结果中有更多行。

然后,在您进行db查询的函数中:

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.";
}

1
投票

您可以使用EXISTS,您的查询应该看起来像这样; SELECT EXISTS (SELECT * FROM COMPANY WHERE imie="John" AND surname="Wattson" AND age=31); 再举一个例子,你可以看看这个; Valid query to check if row exists in SQLite3

© www.soinside.com 2019 - 2024. All rights reserved.