0

私はデータを挿入するためにこのコードを使用していますが、ハードコードにデータを挿入しますが、c ++を使用してユーザー側からデータを挿入する必要があります、誰でも私に主張できます:**

#include <iostream>
 using namespace std;
#include "sqlite3.h"
 int main (int argc, const char * argv[]) {

sqlite3 *db;
sqlite3_open("test1.db", & db);


string createQuery = "CREATE TABLE IF NOT EXISTS items (userid INTEGER PRIMARY KEY, ipaddr TEXT,username TEXT,useradd TEXT,userphone INTEGER,age INTEGER, "
                                                "time TEXT NOT NULL DEFAULT (NOW()));";
  sqlite3_stmt *createStmt;
  cout << "Creating Table Statement" << endl;
  sqlite3_prepare(db, createQuery.c_str(), createQuery.size(), &createStmt, NULL);
  cout << "Stepping Table Statement" << endl;
  if (sqlite3_step(createStmt) != SQLITE_DONE) cout << "Didn't Create Table!" << endl;

  string insertQuery = "INSERT INTO items (time, ipaddr,username,useradd,userphone,age) VALUES ('', '192.167.37.1','rahul da','benerghatta','9966524824',24);"; // WORKS!
  sqlite3_stmt *insertStmt;`enter code here`
  cout << "Creating Insert Statement" << endl;
  sqlite3_prepare(db, insertQuery.c_str(), insertQuery.size(), &insertStmt, NULL);
  cout << "Stepping Insert Statement" << endl;
  if (sqlite3_step(insertStmt) != SQLITE_DONE) cout << "Didn't Insert Item!" << endl;

  string selectQuery = "select * from items where ipaddr='192.167.37.1' & username= 'rahul';";
  sqlite3_stmt *selectStmt;
     cout << "Creating select Statement" << endl;
     sqlite3_prepare(db, selectQuery.c_str(), selectQuery.size(), &selectStmt, NULL);
     cout << "Stepping select Statement" << endl;
     if (sqlite3_step(selectStmt) != SQLITE_DONE) cout << "Didn't Select Item!" << endl;

     cout << "Success!" << endl;

   return 0;
 }
4

1 に答える 1

1

それは本当にあなたが持っているデータから何が保存されているかに依存します。あなたがそれを特定の変数に持っているなら、あなたはあなたがし std::stringsteamたいことを達成するために使うことができます:

std::stringstream insertQuery;
insertQuery << "INSERT INTO items (time, ipaddr,username,useradd,userphone,age)"
               " VALUES ('" << time
            << "', '" << ipaddr
            << "', '" << username
            << "', '" << useradd
            << "', '" << userphone
            << "', " << age << ")";
sqlite3_prepare(db, insertQuery.str().c_str(), insertQuery.size(), &insertStmt, NULL);

.str()文字列を返すためのstringstreamの追加の呼び出しに注意してください。

もちろん、データを挿入する列のタイプに対してデータが有効であることを確認する必要があります。これは、入力がユーザーから直接行われる場合に特に当てはまります。埋め込まれた引用符やメタ文字などの一般的な落とし穴に注意してください。

于 2012-06-07T14:16:46.823 に答える