下载地址:https://download.csdn.net/download/no2101/12428235。
1、sqlite3_exec
static int select_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(" %s \n", (char*)NotUsed);
return 0;
}
void DB_Select_table_test1(sqlite3 *db)
{
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "select_callback function called";
sql = "SELECT * from TESTTABLE";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, select_callback, (void*)data, &zErrMsg);
if (rc != SQLITE_OK) {
printf("SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else {
printf("sqlite3_exec select done successfully\n");
}
}
需要callback
2、sqlite3_get_table
void DB_Select_table_test2(sqlite3 *db)
{
char *errmsg = NULL;
char** dbResult = NULL;
char *sql = "SELECT * from TESTTABLE";
int nRow, nColumn;
int result = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errmsg);
//查询成功
int index = nColumn; //dbResult 前面第一行数据是字段名称,从 nColumn 索引开始才是真正的数据
for (int i = 0; i < nRow; i++)
{
for (int j = 0; j < nColumn; j++)
{
printf("字段名:%s 字段值:%s 长度:%d\n", dbResult[j], dbResult[index], strlen(dbResult[index]));
++index; // dbResult 的字段值是连续的,从第0索引到第 nColumn - 1索引都是字段名称,从第 nColumn 索引开始,后面都是字段值,它把一个二维的表(传统的行列表示法)用一个扁平的形式来表示
}
printf("\n");
}
sqlite3_free_table(dbResult);//释放查询空间
printf("sqlite3_get_table select done successfully\n");
}
速度比较慢,不建议使用。
3、sqlite3_prepare_v2
void DB_Select_table_test3(sqlite3 *db)
{
char *sql = "SELECT * from TESTTABLE;";
sqlite3_stmt * stmt3 = NULL;
if (sqlite3_prepare_v2(db, sql, strlen(sql), &stmt3, NULL) != SQLITE_OK)
{
if (stmt3)
sqlite3_finalize(stmt3);
sqlite3_close(db);
return;
}
int fieldCount = sqlite3_column_count(stmt3);//stmt3返回的是查询结果集
do
{
int r = sqlite3_step(stmt3);
if (r == SQLITE_ROW) {
for (int i = 0; i < fieldCount; ++i) {
int vtype = sqlite3_column_type(stmt3, i);//字段类型获取
//const char* dtype = sqlite3_column_decltype(stmt3, i);//INT REAL之类
const char* otype = sqlite3_column_origin_name(stmt3, i);//申明
printf("%s ", otype);
//判断当前记录当前字段的类型,根据返回的类型使用不同的API函数
//获取实际的数据值
if (vtype == SQLITE_INTEGER) {
int v = sqlite3_column_int(stmt3, i);
printf("is %d.\n", v);
}
else if (vtype == SQLITE_FLOAT) {
double v = sqlite3_column_double(stmt3, i);
printf("is %f.\n", v);
}
else if (vtype == SQLITE_TEXT) {
const char* v = (const char*)sqlite3_column_text(stmt3, i);
printf("is %s.\n", v);
}
else if (vtype == SQLITE_NULL) {
printf("is NULL.\n");
}
}
}
else if (r == SQLITE_DONE) {
printf("finish successfully\n");
break;
}
else {
printf("Failed to SELECT.\n");
sqlite3_finalize(stmt3);
sqlite3_close(db);
return;
}
printf("\n");
} while (true);
printf("sqlite3_prepare_v2 select done successfully\n");
}