使用c ++ sqlite将特定输入插入数据库

时间:2018-03-12 01:49:25

标签: c++ sqlite

我在c ++上很新,并且想知道是否有人可以帮我解决这段代码,基本上它没有错误,但我想要做的是当用户输入他们的名字时,性别,比赛它将它保存到数据库,它创建数据库但不创建表也不插入值名称性别比赛

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 );
    }

1 个答案:

答案 0 :(得分:1)

我不是SQLite for C ++ API的专家,但我可以看到准备好的语句似乎有问题。您应该在?语句中使用INSERT占位符,稍后您将在其中绑定实际值:

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);
    }
}