Home > Enterprise >  How do I get data from an sqlite table in C?
How do I get data from an sqlite table in C?

Time:11-29

I'm trying to create a database using C. I created a table called newCell, and inserted some values into it. Now, I want to iterate through all the rows and get values from 3 of the 6 columns per row. I've been trying to do something similar to this, and this link. It inserts the values into the table, but it does not seem to print them out. I expected to insert values into the table, then iterate through them and print the xCell, yCell, and zCell columns. Below is my code:

`#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
int main()
{

char* err;
sqlite3* db;
sqlite3_stmt* stmt;
sqlite3_open("DB_test.db", &db);
double result;
double x,y,z;
char table[]= "CREATE TABLE IF NOT EXISTS newCell\
    (id INTEGER PRIMARY KEY AUTOINCREMENT,\
    xCell REAL NOT NULL,\
    yCell REAL,\
    zCell REAL,\
    volume REAL,\
    count INTEGER DEFAULT 1,\
    CONSTRAINT name_unique UNIQUE (xCell,yCell,zCell)\
    );";
int rc = sqlite3_exec(db,table, NULL, NULL,&err);

if(rc != SQLITE_OK){
    printf("error1: %s\n", err);
}
for(int i = 0; i<10; i  ){
    char query[]= "INSERT INTO newCell(xCell,yCell,zCell,volume,count)\
            VALUES(3.8,6.3,4.22,2.112,1)\
            ON CONFLICT(xCell,yCell,zCell) DO UPDATE SET count=count 1";

    rc = sqlite3_exec(db,query,NULL,NULL,&err);
    if(rc != SQLITE_OK){
        printf("error2: %s\n", err);
    }

}

double ret = sqlite3_prepare_v2(db,"SELECT xCell,yCell,zCell FROM 
newCell", -1,&stmt,0);
if(ret){
    printf("error3: %g\n",ret);
}
for(int i = 0; i<5; i  )
{
    sqlite3_step(stmt);

    if(ret == SQLITE_ROW){
        x = sqlite3_column_double(stmt,0);
        y = sqlite3_column_double(stmt,1);
        z = sqlite3_column_double(stmt,2);

        printf("%g %g %g",x,y,z);

    } else if(ret == SQLITE_DONE){
        printf("Identifier");
        break;
    } else{
        sqlite3_finalize(stmt);
        printf("some error encountered\n");
        break;
    }
}

sqlite3_finalize(stmt);
sqlite3_close(db);



return 0;
}`

I followed another stackoverflow answer, but did not get the result that I expected. I expected to insert values into the table, then iterate through them and print the xCell, yCell, and zCell columns.

CodePudding user response:

ret is not getting updated during stepping, it still holds the return value of sqlite3_prepare_v2.

for(int i = 0; i<5; i  )
{
    sqlite3_step(stmt);

    if(ret == SQLITE_ROW){

Capture return value of sqlite3_step as below.

for(int i = 0; i<5; i  )
{
    ret = sqlite3_step(stmt);

    if(ret == SQLITE_ROW){
  • Related