0

I am working now with sqlite3. I want to use variable barcode_prog in SELECT. I have file of database sql_db with table PT and columns BarCode and Name. But I want to use anyone string in SELECT, which will set in programm. I ask my question in comment in code. Help, please :)

#include "stdafx.h"
#include "sqlite3.h"
#include <iostream>

int data (void *unused, int field_num, char **value, char **field_name)
{
    for (int i = 0; i < field_num; i++)
    {
        std::cout << value[i] << " = " << field_name[i] << std::endl;
    }
    return 0;
}

int main()
{
    int error;
    char *barcode_prog = "4813538002837";
    char *errmsg;
    sqlite3 *db;
    char *sql = "SELECT * FROM PT WHERE ?"; // here i want to use barcode_prog like     "SELECT * FROM PT WHERE BarCode = barcode_prog"
    error = sqlite3_open("sql_db", &db);
    if (error != SQLITE_OK) 
    {
        std::cout << "Cannot read database" << sqlite3_errmsg(db) << std::endl;
    }

    error = sqlite3_exec(db, sql, data, 0, &errmsg);

    if (error != SQLITE_OK) 
    {
        std::cout << "ERROR!" << errmsg << std::endl;
        sqlite3_free(errmsg);
    }

    system ("pause");
    sqlite3_close(db);
    return 0;
}

1 Answer 1

1

Probably a few ways to do this. I think the simplest is to use std::stringstream.

// your code
std::stringstream stream;
stream << "SELECT * FROM PT WHERE BarCode = " << barcode_prog.
// ...
error = sqlite3_exec(db, stream.str().c_str(), data, 0, &errmsg);
//...
Sign up to request clarification or add additional context in comments.

1 Comment

Hello again. Can you write one more way, please!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.