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

请注意对 stringstream 的附加调用.str()以返回字符串。

当然,您必须确保您的数据对于您要插入的列类型有效。如果您的输入直接来自用户,则尤其如此 - 注意常见的陷阱,例如嵌入式引号和元字符。

于 2012-06-07T14:16:46.823 回答