prismatic
prismatic

Reputation: 13

SQLite C API, can open DB but not returning any data with Query?

I'm trying to use SQLite's C API to open a database and access some records. It seems to open the database fine, but I don't get any results when trying a query (0 rows returned). The same query works in the sqlite3 CLI and other sqlite apps/frontends. I'm using [http://www.sqlite.org/cintro.html] as a reference.

My code is pretty much just two function calls. Program output is:

"Opened DB"

"number of rows = 0".

I'm not doing anything complicated here, so I hope I'm just making a simple mistake somewhere that I don't see. I'd appreciate any help.

-kf

int main()
{
// declare some vars
sqlite3* db_handle;
char sql[2048];     // for commands,queries and such
char* err_msg;
char** results;
int rows, columns;

// connect to database file
if (!(sqlite3_open_v2("../../Downloads/maps/ontario.sql", &db_handle, SQLITE_OPEN_READONLY, NULL)))
{
    std::cerr << "Could not connect to DB" << std::endl;
    std::cerr << "Error: " << sqlite3_errmsg(db_handle);
    sqlite3_close(db_handle);
    return -1;
}
else
{  std::cerr << "Opened DB" << std::endl;  }

// try sending query
strcpy(sql, "SELECT * FROM osm_node_tags LIMIT 10");
if(!(sqlite3_get_table(db_handle, sql, &results, &rows, &columns, &err_msg)))
{
    std::cerr << "Error: " << sqlite3_errmsg(db_handle);
    sqlite3_close(db_handle);
    return -1;
}
else
{
    std::cerr << "number of rows = " << rows;

    for (int i=1; i <= rows; i++)
    {  std::cerr << results[(i * columns) + 0] << std::endl;  }
}


return 1;
}

Upvotes: 1

Views: 301

Answers (2)

Jonathan
Jonathan

Reputation: 1507

http://ray.bsdart.org/man/sqlite/c3ref/open.html

sqlite3_open_v2 returns SQLITE_OK (which is zero) when it's successful. I think your conditionals are upside-down.

Upvotes: 1

msw
msw

Reputation: 43497

I cannot even see any not-so-obvious bugs, so will note that sqlite3_get_table says:

This is a legacy interface that is preserved for backwards compatibility. Use of this interface is not recommended.

but it really shouldn't be broken. Have you double-checked that the table actually contains more than zero rows?

Upvotes: 0

Related Questions