0

I'm quite new at c++ and was wondering if someone could help me out with the piece of code, basically it has no errors but what I'm trying to do is when an user inputs their name, sex, race it'll save it to a database, it creates the database but does not create the table neither does it insert the values name sex race

void Intro()
{

sqlite3 *db;
sqlite3_stmt * st;
string sql3;



    cout << "Enter the name of your hero:\n";
    cin >> name;
    cout << "Enter hero sex: (M/F)\n";
    cin >> sex;
    cout << "Enter hero race: (e.g dwarf,elf,human)\n";
    cin >> race;

   sql3 = "CREATE TABLE PERSONS("  
         "ID INT PRIMARY        KEY      NOT NULL," 
         "NAME         TEXT     NOT NULL," 
         "SEX          TEXT     NOT NULL," 
         "RACE         TEXT     NOT NULL,"

   ;
  string sql = "INSERT INTO PERSONS (name,sex,race) VALUES (" + name + ',' + sex + ',' + race + ");";

    if(sqlite3_open("pw.db", &db) == SQLITE_OK)
    {
        sqlite3_prepare( db, sql.c_str(), -1, &st, NULL);
        sqlite3_bind_text(st, 1, name.c_str(), name.length(), SQLITE_TRANSIENT);
        sqlite3_bind_text(st, 2, sex.c_str(), sex.length(), SQLITE_TRANSIENT);
        sqlite3_bind_text(st, 3, race.c_str(), race.length(), SQLITE_TRANSIENT);
        sqlite3_step( st );
    }
2
  • Still stuck on this :( Commented Mar 12, 2018 at 6:10
  • All function calls must be checked for errors. Commented Mar 12, 2018 at 17:42

1 Answer 1

1

I am not expert in the SQLite for C++ API, but I can see what appears to be a problem with your prepared statement. You should be using ? placeholders in the INSERT statement, into which you bind actual values later on:

if (sqlite3_open("pw.db", &db) == SQLITE_OK)
{
    string sql = "INSERT INTO PERSONS (name, sex, race) VALUES (?, ?, ?);";
    int rc = sqlite3_prepare(db, sql.c_str(), -1, &st, NULL);
    if (rc == SQLITE_OK)
    {
        sqlite3_bind_text(st, 1, name.c_str(), name.length(), SQLITE_TRANSIENT);
        sqlite3_bind_text(st, 2, sex.c_str(),  sex.length(),  SQLITE_TRANSIENT);
        sqlite3_bind_text(st, 3, race.c_str(), race.length(), SQLITE_TRANSIENT);
        sqlite3_step(st);
        sqlite3_finalize(st);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.