c++:如何使用sqlite3从客户端向数据库中插入值

标签 c++ sqlite gsoap

我正在使用这段代码插入数据,但在硬代码中插入数据,但我的需要是使用 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;
 }

最佳答案

这真的取决于你得到的数据存储在什么地方。如果你在特定的变量中得到它,那么你可以使用 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() 以返回字符串。

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

关于c++:如何使用sqlite3从客户端向数据库中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10933301/

相关文章:

c++ - QSqlQuery size() 总是返回 -1

sqlite - 如何在UWP应用程序中的应用程序文件夹之外访问文件(如SQLite数据库)?

c - gSoap 生成的客户端结构初始化和使用

时间:2018-03-08 标签:c++gsoapSO_REUSEADDR

c++ - gSOAP C++ 客户端内存泄漏

c++ - 如何在centos中的c中从IP获取以太网适配器名称

c++ - 从内存中运行进程 C/C++

c++ - 有什么理由重载全局新建和删除?

perl - 如何使用 SQLite 使 DBIx::Class 在 ORDER BY 中忽略大小写?

php - 使用 sqlite 进行搜索索引?