PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How do I store into a C++ variables using sqlite3?

 October 17, 2022     c++, database, int, sqlite     No comments   

Issue

I'm new in the world of C++.

I'm trying to store into a variable a value contained in a sqlite table that I've created but I don't know how to do (I research a lot befor asking here).

So, after I open the DB connection I execute this:

   char* sql = new char[4096];
   strcpy(sql, statement.c_str());

   /* Execute SQL statement */
   int rc = sqlite3_exec(DB, sql, callback, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL ERROR: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "STATEMENT:\n\n%s\n\nEXECUTED SUCCESSFULLY!\n\n", statement.c_str());
   }

And I get this:

OPENED DATABASE SUCCESSFULLY
sent = 0

sent = 0

sent = 0

sent = 0

sent = 0

sent = 1

sent = 1

sent = 1

STATEMENT:

SELECT sent FROM Message;

EXECUTED SUCCESSFULLY!

What I want to do is to store the value contained in "sent" (the datatype in the db is boolean) in a int variables that I can manipulate to check some condition. Or maybe to store all the values into a int array.

How can I do? Please help me!

Thanks a lot!

EDIT: I'm using sqlite3 library.

And this is my callback function:

static int 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("\n");
   return 0;
}

Solution

Don't use sqlite3_exec() for anything that needs to do anything with the results of a query, or anything that involves user-supplied values. Use a prepared statement.

Something like

sqlite3_stmt *stmt;
int rc = sqlite3_prepare_v2(DB, statement.c_str(), statement.length(), &stmt, nullptr);
if (rc != SQLITE_OK) {
 // handle the error
}
// Loop through the results, a row at a time.
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
 int sent = sqlite3_column_int(stmt, 0);
 // etc.
}
// Free the statement when done.
sqlite3_finalize(stmt);


Answered By - Shawn
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing