I am trying to access some names from sqlite3 database and store it to an array of pointer to char using c code
But finally, its assigning the same string repeatedly into all the array of pointers location.
Kindly help me to fix this issue. I tried my level best.. But no improvement. Thanks in advance.
My code:
#include<stdio.h>
#include<stdlib.h>
#include<sqlite3.h>
const char* data = "Callback function called";
sqlite3 *db;
int sql_result;
char *sql;
char *zErrMsg;
int count = 0;
char *store[50];
char **result;
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
static int j = 0;
int i = 0;
printf("\n j_value:%d\n",j);
printf("\n argc: %d", argc);
for(i = 0; i < argc; i++)
{
printf("\n %s = %s", azColName[i], argv[i] ? argv[i] : "NULL");
result[i] = argv[i]; /* Getting database values */
}
if(j < count)
{
store[j] = result[0]; /* Assigning data to array of pointer */
printf("\n output[%d]:%s\n",j, store[j]);
j++;
if(j == count)
j = 0;
}
for(i = 0;i < count;i++)
{
printf("\n Final output[%d]:%s\n",i, store[i]);
}
return 0;
}
int open_db() /* Open database */
{
sql_result = sqlite3_open("test.db", &db);
if( sql_result ){
printf( "Error:%s", sqlite3_errmsg(db));
exit(0);
}else{
//printf("\nsuccess\n");
}
return 0;
}
int exec_db() /* Execute SQL statement */
{
sql_result = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( sql_result != SQLITE_OK ){
printf( "Error:%s", zErrMsg);
sqlite3_free(zErrMsg);
}else{
//printf("\nsuccess\n");
}
return 0;
}
int main()
{
open_db();
result = (char**)calloc(100, sizeof(char*));
sql = "SELECT COUNT(*) FROM test_table;";
exec_db();
count = atoi(result[0]);
sql = (char*)calloc(50, sizeof(char));
sprintf(sql, "SELECT NAME FROM test_table WHERE ID=%d",10);
exec_db();
return 0;
}
Output:
j_value:0
argc: 1
COUNT(*) = 3
j_value:0
argc: 1
name = Jessy
output[0]:Jessy
Final output[0]:Jessy
Final output[1]:(null)
Final output[2]:(null)
j_value:1
argc: 1
name = Hussain
output[1]:Hussain
Final output[0]:Hussain
Final output[1]:Hussain
Final output[2]:(null)
j_value:2
argc: 1
name = Shyam
output[2]:Shyam
Final output[0]:Shyam
Final output[1]:Shyam
Final output[2]:Shyam