I am implementing a function that receives any SQL statement and then executes it.
void dbExec(std::string str, bool vertical)
{
sqlite3 *db; // Create db object
char *zErrMsg = 0;
int rc;
const char *sql = str.c_str(); // Convert string to char
sqlite3_stmt *stmt = NULL; // SQL statement
/* Open Database */
rc = sqlite3_open("db/survey.db",&db);
if (rc)
{
fprintf(stderr, "DBOPEN_ERR: %s\n", sqlite3_errmsg(db));
}
/* Execute SQL statement */
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); // Prepare statement
if (rc != SQLITE_OK )
{ // Check error
fprintf(stderr, "DB error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
int cols = sqlite3_column_count(stmt); // Number of columns
const char *data = NULL; // data char pointer
if (vertical)
{
sqlite3_step( stmt );
for (int i = 0; i < cols; i++)
{
// Print column name and info
data = (const char*)sqlite3_column_text( stmt, i );
std::cout << std::setw(20) << sqlite3_column_name(stmt,i)
<< std::setw(30) << (data ? data : "[NULL]" );
printf("\n");
}
}
else
{
for (int i = 0; i < cols; i++)
{
// Print column name
std::cout << std::setw(15) << sqlite3_column_name(stmt,i);
}
printf("\n");
while ( sqlite3_step( stmt ) == SQLITE_ROW )
{
// print each row
for (int i = 0; i < cols; i++)
{
data = (const char*)sqlite3_column_text( stmt, i );
std::cout << std::setw(15) << (data ? data : "[NULL]" );
}
printf("\n");
}
}
/* Close Database */
sqlite3_close(db);
}
When the str
argument is:
SELECT * FROM TABLE
it works perfect. If the str
argument is:
INSERT INTO TABLE (COL1) VALUES(100)
it doesn't work.
However, if inside of the function I add the following line:
str = "INSERT INTO TABLE (COL1) VALUES(100)";
it works perfect. I tried many things but I still can't figure out what's going on... Any ideas?
Thanks!
EDIT:
The function dbExec
is being called in this way:
void addBorehole()
{
std::string statement;
statement = "INSERT INTO BOREHOLE (TOTAL_DEPTH) VALUES (45)";
dbExec(statement, false);
}