ibadia
ibadia

Reputation: 919

Retrieving data from sqlite3 database( .db file) and storing it in a simple string in c++

I am using visual studio 2015 , basically i want to retrieve SOME data from sqlite database and store it in a string. the following code just displays the data on screen,,, is there any method through which i can store it in a string. PS: i have already created the table through command prompt..

 int main()
 {
   char *zErrMsg = 0;
   sqlite3 *db;
   int rc;
   rc = sqlite3_open("testingvisual.db", &db);

    //string sql;
    char *data;
  const char *sql;
  sql = "INSERT INTO TESTDATA VALUES (1,'test','test2');"; 
    sqlite3_exec(db, sql, callback, 0, &zErrMsg);
    sql = "SELECT * FROM TESTDATA WHERE id=1;";
   sqlite3_exec(db, sql, callback, 0, &zErrMsg);
  }

Upvotes: 0

Views: 2222

Answers (1)

Kathleen
Kathleen

Reputation: 108

When you wish to retrieve data (i.e., process a SELECT statement), use APIs sqlite3_prepare_v2 and sqlite3_step. As you discovered, sqlite3_exec is the right choice for processing INSERT, UPDATE, DELETE and data definition functions. Here's a rough treatment for a SELECT query to get you started:

sqlite3_stmt* t_statement;
sql="SELECT * FROM TESTDATA WHERE id=1;";
size_t t_len = strlen(sql);

int rc = sqlite3_prepare_v2(db, sql, t_len, &t_statement, &zErrMsg);

if (rc == SQLITE_OK)
{
   rc = sqlite3_step(t_statement);
   if (rc == SQLITE_OK)
   {
       // iterate over the columns to get the data
       const char* t_value = 
          sqlite3_column_text(t_statement, [column_number]);
   }
}
else
{
    // zErrMsg may have an error message. If not, the database object
    // may have one. Either way, you can find out what went wrong.
    const char* db_error_msg = sqlite3_errmsg(db);
} 

I keep a browser bookmark set to https://www.sqlite.org/c3ref/funclist.html. FWIW, I built a class to manage my SQLite interactions so that my code could make friendly-to-me calls to the SQLite API functions (e.g., ExecSQL(), SetIsActive(), FetchNext(), GetFieldByName(), etc.) You might want to do something like that, too.

Upvotes: 2

Related Questions